@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.utils

import android.content.Context
import eu.gaudian.translator.model.LanguageModel
import eu.gaudian.translator.model.communication.ApiProvider
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

/**
 * Data classes for parsing the providers configuration JSON
 */
@Serializable
data class ProviderConfig(
    val providers: List<ProviderData>
)

@Serializable
data class ProviderData(
    val key: String,
    val displayName: String,
    val baseUrl: String,
    val endpoint: String,
    val websiteUrl: String,
    val isCustom: Boolean = false,
    val models: List<ModelData>
)

@Serializable
data class ModelData(
    val modelId: String,
    val displayName: String,
    val provider: String,
    val description: String
)

/**
 * Utility class for parsing provider configuration from JSON
 */
object ProviderConfigParser {
    
    private val json = Json { ignoreUnknownKeys = true }
    
    /**
     * Loads and parses the providers configuration from the assets folder
     */
    fun loadProvidersFromAssets(context: Context): List<ApiProvider> {
        return try {
            val jsonString = context.assets.open("providers_config.json")
                .bufferedReader()
                .use { it.readText() }
            
            val config = json.decodeFromString<ProviderConfig>(jsonString)
            
            config.providers.map { providerData ->
                ApiProvider(
                    key = providerData.key,
                    displayName = providerData.displayName,
                    baseUrl = providerData.baseUrl,
                    endpoint = providerData.endpoint,
                    websiteUrl = providerData.websiteUrl,
                    isCustom = providerData.isCustom,
                    models = providerData.models.map { modelData ->
                        LanguageModel(
                            modelId = modelData.modelId,
                            displayName = modelData.displayName,
                            providerKey = modelData.provider,
                            description = modelData.description,
                            isCustom = providerData.isCustom
                        )
                    }
                )
            }
        } catch (e: Exception) {
            Log.e("ProviderConfigParser", "Failed to load providers from JSON", e)
            emptyList()
        }
    }
}