//! `keg env` command — Print environment diagnostics

use anyhow::Result;
use console::{style, Emoji};

/// Print environment information
pub fn env() -> Result<()> {
    println!();
    println!("{} {}", Emoji("🔍", ""), style("Kegani Environment").bold());
    println!("{}", style("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━").dim());
    println!();

    // Rust version
    let rust_version = std::process::Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .unwrap_or_else(|| "not found".to_string());
    print_env_line("Rust", rust_version.trim());

    // Cargo version
    let cargo_version = std::process::Command::new("cargo")
        .arg("--version")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .unwrap_or_else(|| "not found".to_string());
    print_env_line("Cargo", cargo_version.trim());

    // Target triple
    let target = std::env::consts::ARCH;
    let family = std::env::consts::FAMILY;
    let os = std::env::consts::OS;
    print_env_line("Target", &format!("{}/{} ({})", target, family, os));

    // Kegani version
    print_env_line("Kegani", env!("CARGO_PKG_VERSION"));

    // Project check
    let has_cargo = Path::new("Cargo.toml").exists();
    let has_manifest = Path::new("manifest/config/config.yaml").exists();

    println!();
    println!("  {} {}", style("Project:").dim(), if has_cargo { style("✓ Cargo.toml found").green() } else { style("✗ No Cargo.toml").red() });
    println!("  {} {}", style("Config:").dim(), if has_manifest { style("✓ manifest/config found").green() } else { style("✗ No manifest/config").yellow() });

    // Database URL check
    let db_url = std::env::var("DATABASE_URL").ok();
    println!();
    print_env_line("DATABASE_URL", db_url.as_deref().unwrap_or("(not set)"));
    print_env_line("REDIS_URL", std::env::var("REDIS_URL").ok().as_deref().unwrap_or("(not set)"));
    print_env_line("RUST_LOG", std::env::var("RUST_LOG").ok().as_deref().unwrap_or("(not set)"));

    println!();
    println!("{} {}", Emoji("✨", ""), style("Done").dim());
    println!();

    Ok(())
}

use std::path::Path;

fn print_env_line(key: &str, value: &str) {
    println!("  {} {}", style(format!("{key:16}")).dim(), style(value).cyan());
}