package com.tomhempel.rbarometer.questionnaire

import android.util.Log
import org.json.JSONArray
import org.json.JSONObject

/**
 * Parses questionnaire availability conditions from server [conditionJson] / API `condition` objects.
 * Same schema as web dashboard and legacy assets/questionnaire_order.json.
 */
object ConditionJsonParser {
    private const val TAG = "ConditionJsonParser"

    /** App string key for locked-card subtitle / toast (from conditionJson.messageKey). */
    fun messageKey(conditionJson: String?): String? {
        if (conditionJson.isNullOrBlank() || conditionJson.trim() == "{}") return null
        return try {
            JSONObject(conditionJson).optString("messageKey").takeIf { it.isNotBlank() }
        } catch (e: Exception) {
            Log.w(TAG, "messageKey parse failed: ${e.message}")
            null
        }
    }

    fun parse(conditionJson: String?): QuestionItem.Condition? {
        if (conditionJson.isNullOrBlank() || conditionJson.trim() == "{}") return null
        return try {
            parse(JSONObject(conditionJson))
        } catch (e: Exception) {
            Log.w(TAG, "Invalid condition JSON: ${e.message}")
            null
        }
    }

    fun parse(conditionObj: JSONObject?): QuestionItem.Condition? {
        if (conditionObj == null) return null
        if (conditionObj.has("anyOf")) {
            val arr = conditionObj.optJSONArray("anyOf") ?: JSONArray()
            val conditions = mutableListOf<QuestionItem.Condition>()
            for (i in 0 until arr.length()) {
                val sub = arr.optJSONObject(i)
                parse(sub)?.let { conditions.add(it) }
            }
            return QuestionItem.Condition.AnyOf(conditions)
        }
        if (conditionObj.has("alwaysAvailable") && conditionObj.optBoolean("alwaysAvailable", false)) {
            return QuestionItem.Condition.AlwaysAvailable
        }
        val requiresList = mutableListOf<String>()
        if (conditionObj.has("requiresCompleted")) {
            val reqArr = conditionObj.optJSONArray("requiresCompleted")
            if (reqArr != null) {
                for (i in 0 until reqArr.length()) requiresList.add(reqArr.optString(i))
            } else {
                conditionObj.optString("requiresCompleted")?.let { if (it.isNotBlank()) requiresList.add(it) }
            }
        }
        val questionnaire = conditionObj.optString("questionnaire").takeIf { it.isNotBlank() }
        val questionId = conditionObj.optString("questionId").takeIf { it.isNotBlank() }
        val operator = conditionObj.optString("operator").takeIf { it.isNotBlank() }
        val value = conditionObj.optString("value").takeIf { it.isNotBlank() }
        val hasQuestionCheck =
            !questionnaire.isNullOrBlank() && !questionId.isNullOrBlank() &&
                !operator.isNullOrBlank() && value != null
        return when {
            requiresList.isNotEmpty() && hasQuestionCheck ->
                QuestionItem.Condition.Combined(
                    requiresList,
                    QuestionItem.Condition.QuestionCondition(
                        questionnaire!!,
                        questionId!!,
                        operator!!,
                        value!!
                    )
                )
            hasQuestionCheck ->
                QuestionItem.Condition.QuestionCondition(
                    questionnaire!!,
                    questionId!!,
                    operator!!,
                    value!!
                )
            requiresList.isNotEmpty() ->
                QuestionItem.Condition.RequiresCompleted(requiresList)
            else -> null
        }
    }
}
