//! Build command handler
//!
//! Orchestrates project building using ProcessService.

use crate::context::CliContext;
use crate::paths;
use anyhow::Result;
use std::process::Command;

/// Arguments for the build command
#[derive(Debug, Clone)]
pub struct BuildArgs {
    pub release: bool,
    pub target: Option<String>,
}

/// Handle the build command
///
/// Builds the Mecha10 project using cargo.
///
/// # Arguments
///
/// * `ctx` - CLI execution context
/// * `args` - Build command arguments
pub async fn handle_build(ctx: &mut CliContext, args: &BuildArgs) -> Result<()> {
    println!();
    println!("🔨 Building Mecha10 Project");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    // Verify we're in a project
    if !ctx.is_project_initialized() {
        println!("⚠️  Not in a Mecha10 project directory");
        println!();
        return Err(anyhow::anyhow!("Not in a Mecha10 project"));
    }

    // Detect project to ensure it's valid
    let project = ctx.project()?;
    println!("Project: {}", project.name()?);

    if args.release {
        println!("Mode: Release (optimized)");
    } else {
        println!("Mode: Debug");
    }

    if let Some(target) = &args.target {
        println!("Target: {} (cross-compilation)", target);
    } else {
        println!("Target: Host architecture");
    }
    println!();

    // Build using cargo
    println!("Running cargo build...");
    println!();

    let mut cmd = Command::new("cargo");
    cmd.arg("build").current_dir(&ctx.working_dir);

    if args.release {
        cmd.arg("--release");
    }

    if let Some(target_arch) = &args.target {
        cmd.arg("--target").arg(target_arch);
    }

    let status = cmd.status()?;

    println!();

    if status.success() {
        println!("✅ Build completed successfully");
        println!();

        // Show output location
        let build_profile = if args.release { "release" } else { "debug" };
        let target_dir = paths::target_path_with_triple(args.target.as_deref(), build_profile);

        println!("Binaries location: {}", target_dir);
        println!();
    } else {
        println!("❌ Build failed");
        println!();
        return Err(anyhow::anyhow!("Build failed"));
    }

    Ok(())
}
