//! `keg up` command — Update Kegani framework and CLI

use anyhow::{Context, Result};
use console::{style, Emoji};
use std::fs;

/// Update Kegani dependency in Cargo.toml
pub fn update() -> Result<()> {
    // Pin project directory before any subprocess calls
    let project_dir = std::env::current_dir().context("Failed to get current directory")?;
    let cargo_path = project_dir.join("Cargo.toml");

    println!();
    println!("{} {}", Emoji("🚀", ""), style("Updating Kegani").bold());
    println!();

    if !cargo_path.exists() {
        anyhow::bail!("No Cargo.toml found in current directory");
    }

    let content = fs::read_to_string(&cargo_path)?;

    // Simple line-by-line replacement
    let mut updated_lines = Vec::new();
    let mut changed = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("kegani") && trimmed.contains('=') {
            updated_lines.push("kegani = \"0.1\"".to_string());
            changed = true;
        } else {
            updated_lines.push(line.to_string());
        }
    }

    if changed {
        fs::write(&cargo_path, updated_lines.join("\n")).context("Failed to update Cargo.toml")?;
        println!("  {} {}", style("✓").green(), style("Updated Cargo.toml").dim());
    } else {
        println!("  {} {}", style("○").dim(), style("Cargo.toml unchanged (no kegani dep found)").dim());
    }

    // Run cargo update
    let status = std::process::Command::new("cargo")
        .args(["update", "-p", "kegani"])
        .current_dir(&project_dir)
        .status()
        .context("Failed to run cargo update")?;

    if status.success() {
        println!();
        println!("{} {}", Emoji("✅", ""), style("Kegani updated!").green());
        println!("  {} {}", style("→").cyan(), style("cargo build").dim());
    } else {
        anyhow::bail!("cargo update failed");
    }

    Ok(())
}