//! Validate command - runs spec-guard validation

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

/// Run the validate command
pub async fn run(file: Option<String>) -> Result<()> {
    println!("{}", "🔍 Running spec validation...".bold());
    println!();

    let project_root = find_project_root()?;

    match file {
        Some(ref f) if f.ends_with(".sds.yaml") => {
            println!("Validating SDS: {}", f.cyan());
            let output = Command::new("just")
                .args(["sds-validate", f])
                .current_dir(&project_root)
                .output()
                .context("Failed to run sds-validate")?;

            print_output(&output);
        }
        Some(ref f) if f.ends_with(".sea") => {
            println!("Validating SEA-DSL: {}", f.cyan());
            let output = Command::new("just")
                .args(["sea-validate", f])
                .current_dir(&project_root)
                .output()
                .context("Failed to run sea-validate")?;

            print_output(&output);
        }
        Some(ref f) => {
            println!("Validating: {}", f.cyan());
            let output = Command::new("just")
                .arg("spec-guard")
                .current_dir(&project_root)
                .output()
                .context("Failed to run spec-guard")?;

            print_output(&output);
        }
        None => {
            println!("Running full spec-guard validation...");
            println!();
            
            let output = Command::new("just")
                .arg("spec-guard")
                .current_dir(&project_root)
                .output()
                .context("Failed to run spec-guard")?;

            print_output(&output);
        }
    }

    Ok(())
}

fn print_output(output: &std::process::Output) {
    if !output.stdout.is_empty() {
        println!("{}", String::from_utf8_lossy(&output.stdout));
    }
    if !output.stderr.is_empty() {
        eprintln!("{}", String::from_utf8_lossy(&output.stderr));
    }

    if output.status.success() {
        println!("{}", "✅ Validation passed!".green().bold());
    } else {
        println!("{}", "❌ Validation failed".red().bold());
    }
}

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