package com.tomhempel.rbarometer.ui.localization

import com.tomhempel.rbarometer.LanguageManager

/**
 * Shared UI string helpers for upload overview and activities.
 */
object UiStrings {

    fun t(languageId: String, key: String): String =
        LanguageManager.getText(languageId, key)

    /**
     * Resolves UI text for display: selected language, then German API fallback, then [fallback].
     * Avoids showing raw translation keys when possible.
     */
    fun tDisplay(languageId: String, key: String, fallback: String): String {
        tOrNull(languageId, key)?.let { return it }
        tOrNull("GERMAN", key)?.let { return it }
        val raw = t(languageId, key)
        val cleaned = stripBrackets(raw).trim()
        return if (cleaned.equals(key, ignoreCase = true) || cleaned.isBlank()) fallback else cleaned
    }

    fun questionnaireTitleKey(questionnaireId: String): String =
        questionnaireId
            .substringAfter("questionnaire_")
            .substringAfter("_")
            .removeSuffix(".json")
            .ifBlank { questionnaireId }

    fun questionnaireDisplayName(
        languageId: String,
        questionnaireId: String,
        serverName: String?,
    ): String {
        serverName?.takeIf { it.isNotBlank() }?.let { return it }
        val key = questionnaireTitleKey(questionnaireId)
        return tDisplay(languageId, key, questionnaireId)
    }

    /** Like [t] but returns null when translation is missing or equals the key. */
    fun tOrNull(languageId: String, key: String): String? {
        val txt = try {
            LanguageManager.getText(languageId, key)
        } catch (_: Exception) {
            return null
        }
        val out = stripBrackets(txt).trim()
        return if (out.equals(key, ignoreCase = true) || out.isBlank()) null else out
    }

    fun stripBrackets(s: String): String {
        val m = Regex("^\\[(.*)]$").matchEntire(s.trim())
        return m?.groupValues?.get(1) ?: s
    }

    fun localizeQuestionLabel(
        languageId: String,
        questionId: String,
        fallbackQuestionText: String?,
    ): String {
        val field = questionId.substringAfterLast('-', questionId)
        tOrNull(languageId, field)?.let { return it }
        tOrNull(languageId, questionId)?.let { return it }
        fallbackQuestionText?.takeIf { it.isNotBlank() }?.let { return it }
        return field.replace('_', ' ').replaceFirstChar { it.titlecase() }
    }

    fun localizeAnswerValue(languageId: String, fieldId: String, raw: String): String {
        if (raw == "—") return raw
        if (raw.matches(Regex("^\\d{1,4}([./-]\\d{1,2}([./-]\\d{1,4})?)?$"))) return raw
        tOrNull(languageId, raw)?.let { return it }
        val norm = raw.lowercase().replace(Regex("[^a-z0-9]+"), "_").trim('_')
        if (norm.isNotBlank()) tOrNull(languageId, norm)?.let { return it }
        if (norm.isNotBlank()) {
            tOrNull(languageId, "${fieldId}_$norm")?.let { return it }
            tOrNull(languageId, "${fieldId}-$norm")?.let { return it }
        }
        return stripBrackets(raw)
    }

    fun extractQuestionnaireNumber(id: String): Int? {
        val m = Regex("^questionnaire_(\\d+)").find(id.lowercase())
        return m?.groupValues?.get(1)?.toIntOrNull()
    }
}
