package com.tomhempel.rbarometer.questionnaire

import android.app.Activity
import android.util.Log
import android.widget.Toast
import com.tomhempel.rbarometer.LanguageManager
import com.tomhempel.rbarometer.MainActivity

/**
 * Validates questionnaire JSON before the coach opens a flow.
 * Returns an app UI string key when configuration is unusable.
 */
object QuestionnaireValidation {
    private const val TAG = "QN_VALIDATION"

    /** @return app UI string key, or null if the questionnaire can be opened */
    fun configErrorKeyForFile(activity: Activity, filename: String): String? {
        return try {
            val questions = QuestionnaireJsonLoader.load(activity, filename).second
            configErrorKey(questions, filename)
        } catch (e: Exception) {
            Log.e(TAG, "validate file failed: $filename", e)
            "error_invalid_data"
        }
    }

    fun configErrorKey(questions: List<QuestionItem>, questionnaireId: String = ""): String? {
        for (q in questions) {
            val reason = when (q) {
                is QuestionItem.StringSpinnerQuestion -> {
                    val usable = (q.options ?: emptyList()).map { it.trim() }.filter { it.isNotEmpty() }
                    if (usable.isEmpty()) "string_spinner id=${q.id} question=${q.question}" else null
                }
                is QuestionItem.RadioQuestion -> {
                    val usable = (q.options ?: emptyList()).count { it.key.isNotBlank() }
                    if (usable == 0) "radio id=${q.id}" else null
                }
                is QuestionItem.ValueSpinnerQuestion -> {
                    if (!hasValueSpinnerChoices(q)) "value_spinner id=${q.id}" else null
                }
                is QuestionItem.MultiCheckboxQuestion -> {
                    if ((q.options ?: emptyList()).isEmpty()) "multi_checkbox id=${q.id}" else null
                }
                else -> null
            }
            if (reason != null) {
                Log.w(TAG, "missing options in $questionnaireId: $reason")
                return "questionnaire_missing_options"
            }
        }
        return null
    }

    /** Matches [HandlerValueSpinner]: fixed options or numeric range. */
    private fun hasValueSpinnerChoices(q: QuestionItem.ValueSpinnerQuestion): Boolean {
        if ((q.options ?: emptyList()).isNotEmpty()) return true
        val range = q.range ?: return false
        return range.max >= range.min
    }

    fun showConfigError(activity: MainActivity, languageId: String, errorKey: String) {
        val message = LanguageManager.getText(languageId, errorKey)
        Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
    }
}
