use std::path::PathBuf;

use clap::{Parser, ValueEnum};
use tailtriage_analyzer::{analyze_run, render_json_pretty, render_text, AnalyzeOptions};
use tailtriage_cli::artifact::load_run_artifact;

#[derive(Debug, Parser)]
#[command(name = "tailtriage")]
#[command(about = "Analyze tailtriage run artifacts", version)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, clap::Subcommand)]
enum Command {
    /// Analyze one tailtriage run JSON artifact.
    Analyze {
        /// Path to a run JSON file generated by tailtriage-core.
        #[arg(value_name = "RUN_JSON")]
        run_json: PathBuf,
        /// Output format for the diagnosis report.
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
    Text,
    Json,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Command::Analyze { run_json, format } => {
            let loaded = load_run_artifact(&run_json)?;
            for warning in &loaded.warnings {
                eprintln!("warning: {warning}");
            }
            let report = analyze_run(&loaded.run, AnalyzeOptions::default());

            match format {
                OutputFormat::Text => {
                    println!("{}", render_text(&report));
                }
                OutputFormat::Json => {
                    println!("{}", render_json_pretty(&report)?);
                }
            }
        }
    }

    Ok(())
}
