package eu.gaudian.translator.view.hints

import android.content.Context
import java.util.Locale

/**
 * Internationalization system for markdown hints.
 *
 * This follows Android's locale-qualified resource pattern:
 * - assets/hints/           - Default (English)
 * - assets/hints-de-rDE/    - German
 * - assets/hints-pt-rBR/    - Portuguese (Brazil)
 * - etc.
 *
 * Usage:
 * val content = MarkdownHintLoader.loadHint(context, "api_key_hint")
 * MarkdownHintLoader.getHintFileName("api_key_hint") // Returns localized filename
 */
object MarkdownHintLoader {

    /**
     * Load markdown content with automatic locale detection.
     *
     * @param context The context for accessing assets
     * @param hintFileName The base filename without locale suffix (e.g., "api_key_hint")
     * @return The markdown content as a string, or null if not found
     */
    fun loadHint(context: Context, hintFileName: String): String? {
        val locale = getCurrentLocale(context)
        val suffix = getLocaleSuffix(locale)
        
        // Try localized version (folder has suffix, filename doesn't)
        val localizedPath = "hints$suffix/$hintFileName.md"
        val localizedContent = loadFromAssets(context, localizedPath)
        if (localizedContent != null) {
            return localizedContent
        }

        // Try with just language code (e.g., hints-pt/ instead of hints-pt-rBR/)
        val languageSuffix = if (locale.country.isNotEmpty()) "-${locale.language}" else ""
        val languageOnlyPath = "hints$languageSuffix/$hintFileName.md"
        val languageContent = loadFromAssets(context, languageOnlyPath)
        if (languageContent != null) {
            return languageContent
        }

        // Fall back to default (English) in hints folder
        val defaultPath = "hints/$hintFileName.md"
        val defaultContent = loadFromAssets(context, defaultPath)
        if (defaultContent != null) {
            return defaultContent
        }

        return null
    }

    /**
     * Get the localized file path for a hint.
     *
     * @param hintFileName The base filename (e.g., "api_key_hint")
     * @return The full path including locale folder (e.g., "hints-de-rDE/api_key_hint.md")
     */
    fun getHintPath(hintFileName: String): String {
        val locale = Locale.getDefault()
        val localeSuffix = getLocaleSuffix(locale)
        return "hints$localeSuffix/$hintFileName.md"
    }

    /**
     * Get the localized file name for a hint.
     *
     * @param hintFileName The base filename (e.g., "api_key_hint")
     * @param locale The target locale
     * @return The file name with locale suffix (e.g., "api_key_hint-de-rDE.md")
     */
    fun getLocalizedFileName(hintFileName: String, locale: Locale): String {
        val localeSuffix = getLocaleSuffix(locale)
        return "$hintFileName$localeSuffix.md"
    }

    /**
     * Get the file name with language-only suffix.
     *
     * @param hintFileName The base filename
     * @param locale The target locale
     * @return The file name with language suffix (e.g., "api_key_hint-de.md")
     */
    private fun getLanguageOnlyFileName(hintFileName: String, locale: Locale): String {
        val languageCode = locale.language
        return "$hintFileName-$languageCode.md"
    }


    fun getCurrentLocale(context: Context): Locale {
        return context.resources.configuration.locale
    }

    /**
     * Get all supported locales for hints.
     */
    fun getSupportedLocales(): List<Locale> {
        return listOf(
            Locale.ENGLISH,           // Default
            Locale.GERMAN, // de-rDE
            Locale("pt", "BR"),       // pt-rBR
            Locale.FRENCH,           // fr-rFR
            Locale("es", "ES"),       // es-rES
            Locale.ITALIAN,           // it-rIT
            Locale("nl", "NL"),       // nl-rNL
            Locale("hr", "HR")        // hr-rHR
        )
    }

    /**
     * Check if a localized version exists for the given locale.
     */
    fun localizedVersionExists(context: Context, hintFileName: String, locale: Locale): Boolean {
        val localizedFileName = getLocalizedFileName(hintFileName, locale)
        val suffix = getLocaleSuffix(locale)
        return assetExists(context, "hints$suffix/$localizedFileName")
    }

    /**
     * Load content from assets.
     */
    fun loadFromAssets(context: Context, fileName: String): String? {
        return try {
            context.assets.open(fileName).bufferedReader().use { it.readText() }
        } catch (e: Exception) {
            null
        }
    }

    /**
     * Check if an asset file exists.
     */
    private fun assetExists(context: Context, path: String): Boolean {
        return try {
            context.assets.open(path).close()
            true
        } catch (e: Exception) {
            false
        }
    }

    /**
     * Get the locale suffix string.
     */
    fun getLocaleSuffix(locale: Locale): String {
        val language = locale.language
        val country = locale.country

        return buildString {
            if (language.isNotEmpty()) {
                append("-")
                append(language.lowercase())
            }
            if (country.isNotEmpty()) {
                append("-r")
                append(country.uppercase())
            }
        }
    }
}

/**
 * Extension function to get localized hint content.
 */
fun Context.loadLocalizedHint(hintFileName: String): String? {
    return MarkdownHintLoader.loadHint(this, hintFileName)
}

/**
 * Data class for localized hint information.
 */
data class LocalizedHint(
    val fileName: String,
    val locale: Locale,
    val isDefault: Boolean = false
)

/**
 * Hint localization manager that tracks available translations.
 */
object HintLocalizationManager {

    /**
     * Get all available translations for a hint.
     */
    fun getAvailableTranslations(context: Context, baseFileName: String): List<LocalizedHint> {
        val available = mutableListOf<LocalizedHint>()
        val defaultLocale = MarkdownHintLoader.getCurrentLocale(context)

        // Check each supported locale
        MarkdownHintLoader.getSupportedLocales().forEach { locale ->
            val fileName = MarkdownHintLoader.getLocalizedFileName(baseFileName, locale)
            val path = "hints${MarkdownHintLoader.getLocaleSuffix(locale)}/$fileName"

            if (MarkdownHintLoader.loadFromAssets(context, path) != null) {
                available.add(LocalizedHint(
                    fileName = fileName,
                    locale = locale,
                    isDefault = locale.language == "en" && locale.country.isEmpty()
                ))
            }
        }

        return available.sortedBy { it.locale.language }
    }

    /**
     * Get the best available translation for current locale.
     */
    fun getBestTranslation(context: Context, baseFileName: String): String? {
        return MarkdownHintLoader.loadHint(context, baseFileName)
    }
}
