//! `fafb-q health` command — server health checks.
//!
//! Uses the HTTP health endpoints:
//! - `GET /health/ready` — readiness probe (default)
//! - `GET /health/live` — liveness probe (`--live`)
//!
//! Exit code: 0 = healthy, 1 = unhealthy.

use colored::Colorize;

use super::{CliConfig, CliError, HealthArgs, OutputFormat, build_http_client, http_base_url};

pub async fn run(config: CliConfig, args: HealthArgs) -> Result<(), CliError> {
    let format = OutputFormat::auto_detect(config.json, false);
    let client = build_http_client(&config)?;
    let base = http_base_url(&config);

    let path = if args.live {
        "/health/live"
    } else {
        "/health/ready"
    };
    let url = format!("{base}{path}");

    let resp = client.get(&url).send().await.map_err(|e| {
        if e.is_timeout() {
            CliError::Timeout(format!("health check timed out: {e}"))
        } else if e.is_connect() {
            CliError::Error(format!("cannot connect to {}: {e}", config.http_server))
        } else {
            CliError::Error(format!("health check failed: {e}"))
        }
    })?;

    let status = resp.status();

    // Health endpoints should return JSON, but handle non-JSON gracefully.
    let body = super::response_json(resp).await?;

    let health_status = body
        .get("status")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    match format {
        OutputFormat::Json => {
            println!("{body}");
        }
        _ => {
            let label = if args.live { "liveness" } else { "readiness" };
            let colored_status = if status.is_success() {
                health_status.green().to_string()
            } else {
                health_status.red().to_string()
            };
            println!("{} {colored_status}", format!("{label}:").dimmed());
        }
    }

    if status.is_success() {
        Ok(())
    } else {
        Err(CliError::Error(format!("unhealthy: {health_status}")))
    }
}
