//! Pre-flight: every reference solution under master/tasks/ must
//! reach green through the harness pipeline locally (no API call).
//! This is the parent spec §Pre-flight item 4 enforced as a test.

use std::path::PathBuf;
use xmodel_harness::pipeline::{run_pipeline, Cohort};
use xmodel_harness::tasks;

fn master_tasks_dir() -> PathBuf {
    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    manifest.parent().unwrap().join("master").join("tasks")
}

#[test]
fn every_reference_solution_reaches_green() {
    let tasks_dir = master_tasks_dir();
    let tasks = tasks::load_all(&tasks_dir).expect("loading tasks");
    assert!(!tasks.is_empty(), "no tasks loaded from {}", tasks_dir.display());

    let mut failures: Vec<String> = Vec::new();
    for t in &tasks {
        let ref_path = tasks_dir.join(&t.reference_solution);
        let program = std::fs::read_to_string(&ref_path)
            .unwrap_or_else(|e| panic!("read {}: {e}", ref_path.display()));
        let workdir = tempfile::Builder::new().prefix("cma2-ref-").tempdir().unwrap();
        let cap = run_pipeline(Cohort::Json, &program, &t.expected_stdout, workdir.path())
            .unwrap_or_else(|e| panic!("pipeline failed for {}: {e}", t.id));
        if let Some(err) = cap.error {
            failures.push(format!("{}: {}", t.id, err));
        }
    }
    if !failures.is_empty() {
        panic!("{} reference(s) failed pipeline:\n  {}", failures.len(), failures.join("\n  "));
    }
}
