use std::env;
use std::path::Path;
use std::process;

use pdfmake_rust::benchmark_report::{format_markdown_report, format_text_report, run_comparison};

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut baseline_path: Option<String> = None;
    let mut current_path: Option<String> = None;
    let mut thresholds_path: Option<String> = None;

    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--baseline" => {
                i += 1;
                baseline_path = args.get(i).cloned();
            }
            "--current" => {
                i += 1;
                current_path = args.get(i).cloned();
            }
            "--thresholds" => {
                i += 1;
                thresholds_path = args.get(i).cloned();
            }
            "--help" | "-h" => {
                print_usage();
                process::exit(0);
            }
            other => {
                eprintln!("Unknown argument: {}", other);
                print_usage();
                process::exit(1);
            }
        }
        i += 1;
    }

    let baseline = match baseline_path {
        Some(p) => p,
        None => {
            eprintln!("Error: --baseline <path> is required");
            print_usage();
            process::exit(1);
        }
    };

    let current = match current_path {
        Some(p) => p,
        None => {
            eprintln!("Error: --current <path> is required");
            print_usage();
            process::exit(1);
        }
    };

    let thresholds = thresholds_path.unwrap_or_else(|| "benchmarks/thresholds.json".to_string());

    let results = match run_comparison(
        Path::new(&baseline),
        Path::new(&current),
        Path::new(&thresholds),
    ) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(1);
        }
    };

    if results.is_empty() {
        eprintln!("Warning: No benchmark results to compare");
        process::exit(0);
    }

    let md_report = format_markdown_report(&results);
    println!("{}", md_report);

    println!();
    let text_report = format_text_report(&results);
    println!("{}", text_report);

    let any_fail = results.iter().any(|r| r.status == "失败");
    if any_fail {
        process::exit(1);
    }
}

fn print_usage() {
    eprintln!("Usage: benchmark_compare --baseline <path> --current <path> [--thresholds <path>]");
    eprintln!();
    eprintln!("Compare benchmark results against a baseline.");
    eprintln!();
    eprintln!("Options:");
    eprintln!("  --baseline <path>     Path to baseline JSON file");
    eprintln!("  --current <path>      Path to current results JSON file");
    eprintln!("  --thresholds <path>   Path to thresholds JSON (default: benchmarks/thresholds.json)");
    eprintln!("  -h, --help            Show this help message");
}
