//! Init command - initialize or refresh SEA-Forge project

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

/// Run the init command
pub async fn run(yes: bool, dry_run: bool) -> Result<()> {
    println!("{}", "🏗️ Initializing SEA-Forge project...".bold());
    println!();

    let project_root = find_project_root()?;

    if dry_run {
        println!("{} Would run: just setup", "[DRY-RUN]".cyan());
        return Ok(());
    }

    if !yes {
        println!("This will install/update project dependencies.");
        println!("Continue? [Y/n] ");
        // For now, assume yes in non-interactive mode
    }

    // Run just setup
    println!("{}", "Installing dependencies...".dimmed());
    
    let output = Command::new("just")
        .arg("setup")
        .current_dir(&project_root)
        .output()
        .context("Failed to run just setup")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Setup failed: {}", stderr);
    }

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