package com.correx.infrastructure.inference

import com.correx.core.events.types.ProviderId
import com.correx.core.inference.InferenceProvider
import com.correx.core.inference.ModelCapability
import com.correx.core.inference.ProviderHealth
import com.correx.core.inference.ProviderRegistry
import java.util.concurrent.*

/**
 * In-memory [ProviderRegistry] backed by a [CopyOnWriteArrayList] for safe concurrent reads.
 *
 * Providers supplied at construction are registered immediately.
 * Additional providers may be registered at any time via [register].
 */
class DefaultProviderRegistry(
    initialProviders: List<InferenceProvider> = emptyList(),
) : ProviderRegistry {

    private val providers: CopyOnWriteArrayList<InferenceProvider> =
        CopyOnWriteArrayList(initialProviders)

    override fun register(provider: InferenceProvider) {
        providers.add(provider)
    }

    override fun resolve(capability: ModelCapability): List<InferenceProvider> =
        providers
            .filter { p -> p.capabilities().any { it.capability == capability } }
            .sortedByDescending { p ->
                p.capabilities().firstOrNull { it.capability == capability }?.score ?: 0.0
            }

    override fun listAll(): List<InferenceProvider> = providers.toList()

    override suspend fun healthCheckAll(): Map<ProviderId, ProviderHealth> =
        providers.associate { it.id to it.healthCheck() }
}
