package com.correx.apps.server.routes

import com.correx.apps.server.ServerModule
import com.correx.apps.server.protocol.ProviderHealthDto
import com.correx.core.inference.ProviderHealth
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import kotlinx.serialization.Serializable

fun Route.providerRoutes(module: ServerModule) {
    get("/providers") {
        val providers = module.providerRegistry.listAll()
        val healthMap = runCatching { module.providerRegistry.healthCheckAll() }.getOrDefault(emptyMap())
        val response = providers.map { provider ->
            val health = healthMap[provider.id]
            val dto = when (health) {
                is ProviderHealth.Healthy -> ProviderHealthDto(provider.id.value, "healthy", null)
                is ProviderHealth.Degraded -> ProviderHealthDto(provider.id.value, "degraded", null)
                is ProviderHealth.Unavailable -> ProviderHealthDto(provider.id.value, "unavailable", null)
                null -> ProviderHealthDto(provider.id.value, "unknown", null)
            }
            ProviderStatusEntry(providerId = provider.id.value, name = provider.name, health = dto)
        }
        call.respond(response)
    }
}

@Serializable
data class ProviderStatusEntry(val providerId: String, val name: String, val health: ProviderHealthDto)
