//! `keg console` command — Interactive Rust REPL using evcxr

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

/// Start interactive Rust REPL (evcxr)
pub fn console(package: Option<&str>) -> Result<()> {
    println!();
    println!("{} {}", Emoji("🎮", ""), style("Starting Rust REPL (evcxr)").bold());
    println!();

    // Check if evcxr is installed
    if !is_evcxr_installed() {
        println!("  {} {}", style("ℹ").dim(), style("Installing evcxr...").dim());
        install_evcxr()?;
    }

    let project_dir = std::env::current_dir().context("Failed to get current directory")?;

    // Build command
    let mut cmd = Command::new("evcxr");

    // If package is specified, load it
    if let Some(pkg) = package {
        println!("  {} {}", style("→").cyan(), style(format!("Loading package: {}", pkg)).dim());
        cmd.arg("--package");
        cmd.arg(pkg);
    } else {
        // Check if we're in a workspace and offer to load kegani
        let cargo_toml = project_dir.join("Cargo.toml");
        if cargo_toml.exists() {
            println!("  {} {}", style("ℹ").dim(), style("No package specified. Starting with current project.").dim());
        }
    }

    // Pass control to evcxr
    cmd.current_dir(&project_dir);

    println!();
    println!("  {} {}", style("→").cyan(), style("Type :help for help, :q to quit").dim());
    println!();

    let status = cmd.status().context("Failed to start evcxr. Is evcxr installed?")?;

    if !status.success() {
        anyhow::bail!("evcxr exited with error");
    }

    Ok(())
}

fn is_evcxr_installed() -> bool {
    Command::new("evcxr")
        .arg("--version")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

fn install_evcxr() -> Result<()> {
    let status = Command::new("cargo")
        .args(["install", "evcxr"])
        .status()
        .context("Failed to install evcxr")?;

    if !status.success() {
        anyhow::bail!("Failed to install evcxr. Run `cargo install evcxr` manually.");
    }

    println!("  {} {}", style("✓").green(), style("evcxr installed!").green());
    Ok(())
}
