@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import eu.gaudian.translator.model.grammar.LanguageConfig
import eu.gaudian.translator.model.repository.LanguageConfigRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class LanguageConfigViewModel @Inject constructor(
    application: Application,
    private val languageConfigRepository: LanguageConfigRepository
) : AndroidViewModel(application) {

    val configs: StateFlow<Map<String, LanguageConfig>> = languageConfigRepository.configs

    val allWordClasses: StateFlow<List<String>> = configs.map { configsMap ->
        configsMap.values
            .flatMap { it.categories.keys }
            .distinct()
            .sorted()
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    /**
     * Retrieves the configuration for a specific language code.
     *
     * @param langCode The ISO language code (e.g., "de").
     * @return The LanguageConfig for the given code, or null if not found.
     */
    @Suppress("unused")
    fun getConfigForLanguage(langCode: String): LanguageConfig? {
        return languageConfigRepository.getConfigForLanguage(langCode)
    }

    /**
     * Retrieves the set of articles for a specific language code.
     * This method is robust and will not crash if the language or articles are not found.
     *
     * @param langCode The ISO language code (e.g., "de").
     * @return A Set<String> of articles for the given language. Returns an empty set if
     * the language code is not found or if the language has no articles defined.
     */
    fun getArticlesForLanguage(langCode: String): Set<String> {
        return languageConfigRepository.getArticlesForLanguage(langCode)
    }
}
