//! Down command - stops all SEA services

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

/// Run the down command
pub async fn run(volumes: bool, dry_run: bool) -> Result<()> {
    println!("{}", "🛑 Stopping SEA services...".bold());
    println!();

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

    if dry_run {
        println!("{} Would run: docker compose down", "[DRY-RUN]".cyan());
        if volumes {
            println!("{} Would remove volumes (destructive)", "[DRY-RUN]".cyan());
        }
        return Ok(());
    }

    // Stop LibreChat stack
    println!("{}", "Stopping LibreChat stack...".dimmed());
    
    let mut cmd = Command::new("docker");
    cmd.args(["compose", "down"]);
    if volumes {
        cmd.arg("-v");
    }
    cmd.current_dir(&librechat_dir);

    let output = cmd.output().context("Failed to run docker compose down")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("{}", format!("Warning: {}", stderr).yellow());
    }

    // Stop skeleton services
    println!("{}", "Stopping skeleton services...".dimmed());
    let _ = Command::new("just")
        .arg("skeleton-down")
        .current_dir(&project_root)
        .output();

    println!();
    println!("{}", "✅ Services stopped".green().bold());
    
    if !volumes {
        println!();
        println!(
            "💡 Data is preserved. Use {} to destroy volumes.",
            "sea-forge down --volumes".cyan()
        );
    }

    Ok(())
}

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")?;
    }
}
