use metacrate_ci_matrix::{audit, load, run, workspace_root};
use std::path::{Path, PathBuf};

fn main() {
    if let Err(error) = execute() {
        eprintln!("ci-matrix: {error}");
        std::process::exit(1);
    }
}

fn execute() -> Result<(), Box<dyn std::error::Error>> {
    let current = std::env::current_dir()?;
    let root = workspace_root(&current).ok_or("could not locate the Cargo workspace")?;
    let matrix = load(&root)?;
    let mut arguments = std::env::args().skip(1);
    match arguments.next().as_deref() {
        Some("audit") if arguments.next().is_none() => {
            audit(&root, &matrix)?;
            println!(
                "release CI matrix: {} validated profiles; Linux, Windows, macOS, MSRV, stable, default/minimal/optional features, tests, examples, and docs covered",
                matrix.profiles.len()
            );
        }
        Some("run") => {
            let profile = arguments.next().ok_or("run requires a profile")?;
            let flag = arguments.next().ok_or("run requires --evidence FILE")?;
            let evidence = arguments.next().ok_or("run requires --evidence FILE")?;
            if flag != "--evidence" || arguments.next().is_some() {
                return Err("usage: ci-matrix run PROFILE --evidence FILE".into());
            }
            let evidence = absolute_or_rooted(&root, &evidence);
            run(&root, &matrix, &profile, &evidence)?;
            println!("release CI profile {profile}: ok ({})", evidence.display());
        }
        _ => return Err("usage: ci-matrix audit | run PROFILE --evidence FILE".into()),
    }
    Ok(())
}

fn absolute_or_rooted(root: &Path, value: &str) -> PathBuf {
    let path = PathBuf::from(value);
    if path.is_absolute() {
        path
    } else {
        root.join(path)
    }
}
