//! Status command - check service status

use anyhow::{Context, Result};
use colored::Colorize;
use std::process::Command;

/// Run the status command
pub async fn run() -> Result<()> {
    println!("{}", "🏥 SEA Services Status".bold());
    println!();

    let project_root = find_project_root()?;
    let librechat_dir = project_root.join("deploy/librechat");

    // Docker containers status
    println!("{}", "Docker Containers:".bold().underline());
    
    if librechat_dir.exists() {
        let output = Command::new("docker")
            .args(["compose", "ps", "--format", "table {{.Name}}\t{{.Status}}\t{{.Ports}}"])
            .current_dir(&librechat_dir)
            .output();

        match output {
            Ok(o) if o.status.success() => {
                let stdout = String::from_utf8_lossy(&o.stdout);
                if stdout.trim().is_empty() {
                    println!("  {}", "No containers running".dimmed());
                } else {
                    for line in stdout.lines() {
                        println!("  {}", line);
                    }
                }
            }
            _ => println!("  {}", "Unable to get container status".dimmed()),
        }
    } else {
        println!("  {}", "LibreChat not configured".dimmed());
    }

    println!();
    println!("{}", "Health Checks:".bold().underline());

    // Health checks
    let services = [
        ("LibreChat", "http://localhost:3080", 3080),
        ("SEA API", "http://localhost:8080/health", 8080),
        ("Oxigraph", "http://localhost:7878", 7878),
        ("OPA", "http://localhost:8181/health", 8181),
        ("Ollama", "http://localhost:11434/api/tags", 11434),
    ];

    for (name, url, _port) in &services {
        let status = check_url(url);
        match status {
            Ok(_) => println!("  {} {} {}", "✓".green(), name, url.dimmed()),
            Err(_) => println!("  {} {} {}", "✗".red(), name, "Not available".dimmed()),
        }
    }

    Ok(())
}

fn check_url(url: &str) -> Result<(), ()> {
    let output = Command::new("curl")
        .args(["-sf", "--max-time", "2", url])
        .output();

    match output {
        Ok(o) if o.status.success() => Ok(()),
        _ => Err(()),
    }
}

fn find_project_root() -> Result<std::path::PathBuf> {
    let current = std::env::current_dir()?;
    let mut path = current.as_path();

    loop {
        if path.join("justfile").exists() && path.join("Cargo.toml").exists() {
            return Ok(path.to_path_buf());
        }
        path = path.parent().context("Could not find SEA project root")?;
    }
}
