//! Setup command - interactive setup for LibreChat + Zed IDE

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

/// Run the setup command
pub async fn run(skip_zed: bool, skip_librechat: bool, dry_run: bool) -> Result<()> {
    println!("{}", "🔧 Running interactive setup...".bold());
    println!();

    let project_root = find_project_root()?;

    if dry_run {
        if !skip_librechat {
            println!("{} Would configure LibreChat", "[DRY-RUN]".cyan());
        }
        if !skip_zed {
            println!("{} Would configure Zed IDE", "[DRY-RUN]".cyan());
        }
        return Ok(());
    }

    // Run the existing ui-setup script
    println!("{}", "Running UI services setup...".dimmed());
    
    let mut env_vars = vec![];
    if skip_zed {
        env_vars.push(("SKIP_ZED", "1"));
    }
    if skip_librechat {
        env_vars.push(("SKIP_LIBRECHAT", "1"));
    }

    let mut cmd = Command::new("just");
    cmd.arg("ui-setup");
    cmd.current_dir(&project_root);
    for (key, value) in env_vars {
        cmd.env(key, value);
    }

    let output = cmd.output().context("Failed to run ui-setup")?;

    if !output.stdout.is_empty() {
        println!("{}", String::from_utf8_lossy(&output.stdout));
    }

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

    println!();
    println!("{}", "✅ Setup complete!".green().bold());
    println!();
    println!("Next steps:");
    println!("  {} Start services", "sea-forge up".cyan());
    println!("  {} Check status", "sea-forge status".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")?;
    }
}
