//! Handler for `mcptest bakeoff` (WOR-1428).
//!
//! Loads the embedded, pinned competitor matrix and renders a dated scorecard.
//! `--fail-on-gap` turns the gap list into a release gate.

use anyhow::{Context, Result};

use mcptest_core::bakeoff::{render_markdown, BakeoffMatrix};

use crate::cli::args::{BakeoffArgs, BakeoffFormat};
use crate::cli::exit_codes::{EXIT_COVERAGE_FLOOR, EXIT_OK};

/// Render the bakeoff scorecard.
pub(crate) fn bakeoff_command(args: &BakeoffArgs) -> Result<i32> {
    let matrix = BakeoffMatrix::embedded().context("loading the bakeoff matrix")?;

    let body = match args.format {
        BakeoffFormat::Markdown => render_markdown(&matrix),
        BakeoffFormat::Json => format!("{}\n", serde_json::to_string_pretty(&matrix)?),
    };

    match &args.out {
        Some(path) => {
            super::overwrite::ensure_overwritable(path, args.force)?;
            std::fs::write(path, &body).with_context(|| format!("writing {}", path.display()))?;
            eprintln!("wrote the bakeoff scorecard to {}", path.display());
        }
        None => print!("{body}"),
    }

    let gaps = matrix.gaps();
    if !gaps.is_empty() {
        eprintln!(
            "mcptest has {} open capability gap(s) in this snapshot (each tracked in Linear)",
            gaps.len()
        );
        if args.fail_on_gap {
            return Ok(EXIT_COVERAGE_FLOOR);
        }
    }
    Ok(EXIT_OK)
}
