package com.correx.apps.cli.commands

import com.correx.apps.cli.CorrexCli
import com.correx.apps.cli.DEFAULT_PORT
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive

class ProviderCommand : CliktCommand(name = "provider") {
    override fun run() = Unit

    init {
        subcommands(ProviderListCommand())
    }
}

class ProviderListCommand : CliktCommand(name = "list") {
    private val host by option("--host").default("localhost")
    private val port by option("--port").default("$DEFAULT_PORT")

    private val providerJson = Json { ignoreUnknownKeys = true }

    override fun run(): Unit = runBlocking {
        val portInt = port.toIntOrNull() ?: DEFAULT_PORT
        val outputJson = (currentContext.findRoot().command as? CorrexCli)?.json ?: false

        val client = HttpClient(CIO) {
            install(ContentNegotiation) { json(providerJson) }
        }

        runCatching {
            val resp = client.get("http://$host:$portInt/providers")
            val body = resp.body<JsonArray>()
            if (outputJson) {
                println(body.toString())
            } else {
                body.forEach { el ->
                    val obj = el as? JsonObject ?: return@forEach
                    val providerId = obj["providerId"]?.jsonPrimitive?.content ?: ""
                    val status = obj["status"]?.jsonPrimitive?.content ?: ""
                    val load = obj["loadPercent"]?.jsonPrimitive?.content ?: "?"
                    println("$providerId  status=$status  load=${load}%")
                }
            }
        }.getOrElse { e ->
            System.err.println("Error fetching providers: ${e.message}")
        }

        client.close()
    }
}
