//! Conformance corpus for the fleet (`live-conformance/fleet/`,
//! extensions/fleet.md §11).
//!
//!   wai_fleet_vectors gen     <corpus-dir>   write vectors.json, from fixed seeds and the
//!                                          records of the metering corpus
//!   wai_fleet_vectors verify  <corpus-dir>   vectors.json regenerates byte for byte, and
//!                                          every vector gets the outcome it states
//!
//! The corpus directory is `wai/live-conformance/fleet`; the metering corpus it reads is found
//! from it. The generator and this verifier are one implementation. The corpus's second
//! implementation is `live-conformance/fleet_verify.py`, written from the extension's text and
//! sharing no code with this binary.

use std::path::{Path, PathBuf};
use wai::fleet::corpus;

fn wai_dir(corpus_dir: &Path) -> PathBuf {
    corpus_dir.join("..").join("..")
}

fn main() {
    let a: Vec<String> = std::env::args().collect();
    match (a.get(1).map(String::as_str), a.get(2)) {
        (Some("gen"), Some(d)) => {
            let p = Path::new(d).join("vectors.json");
            let text = match corpus::generate(&wai_dir(Path::new(d))) {
                Ok(t) => t,
                Err(e) => {
                    eprintln!("generate: {e}");
                    std::process::exit(1);
                }
            };
            if let Err(e) = std::fs::create_dir_all(d).and_then(|_| std::fs::write(&p, text)) {
                eprintln!("write {}: {e}", p.display());
                std::process::exit(1);
            }
            println!("wrote {}", p.display());
        }
        (Some("verify"), Some(d)) => std::process::exit(verify(Path::new(d))),
        _ => {
            eprintln!("usage: wai_fleet_vectors gen|verify <corpus-dir>");
            std::process::exit(2);
        }
    }
}

fn verify(dir: &Path) -> i32 {
    let p = dir.join("vectors.json");
    let doc = match std::fs::read_to_string(&p) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("read {}: {e}", p.display());
            return 1;
        }
    };
    let mut fail = 0;
    let same = corpus::generate(&wai_dir(dir)).is_ok_and(|g| g == doc);
    println!("{} vectors.json regenerates byte for byte from its seeds and the metering corpus", if same { "PASS" } else { "FAIL" });
    fail += (!same) as i32;
    let fails = corpus::verify(&doc);
    for f in &fails {
        println!("FAIL {f}");
    }
    println!("{} every vector gets the outcome the corpus states", if fails.is_empty() { "PASS" } else { "FAIL" });
    fail += (!fails.is_empty()) as i32;
    (fail != 0) as i32
}
