//! `mcptest schema` prints the embedded JSON Schema to stdout.
//!
//! The schema is compiled into the binary via `include_str!` so the output is
//! byte-identical to `schemas/v1.json` and works without a filesystem read.

use std::io::{self, Write};

use anyhow::Result;

/// Embedded copy of `schemas/v1.json`.
///
/// Same source the loader uses, kept here as well so a stripped binary still
/// prints the schema even if the loader crate is never linked at runtime. The
/// copy is vendored in-crate (kept in sync with the canonical workspace-root
/// `schemas/v1.json` by `scripts/check-vendored-assets.sh`) so `cargo publish`
/// packages it.
const SCHEMA_V1: &str = include_str!("../../schemas/v1.json");

/// Schema versions accepted by `mcptest schema --version`.
///
/// Held as a string slice match so a future `v2` lands as a separate arm
/// without changing the calling convention.
pub fn run_schema(version: &str) -> Result<i32> {
    let body = match version {
        "v1" => SCHEMA_V1,
        other => {
            eprintln!("mcptest schema: unknown version `{other}`. Supported: v1 (default).");
            return Ok(2);
        }
    };
    let stdout = io::stdout();
    let mut handle = stdout.lock();
    handle.write_all(body.as_bytes())?;
    Ok(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn embedded_schema_parses_as_json() {
        let value: serde_json::Value =
            serde_json::from_str(SCHEMA_V1).expect("embedded schema is JSON");
        assert!(value.get("$id").is_some(), "schema carries $id");
    }

    #[test]
    fn unknown_version_returns_exit_two() {
        let code = run_schema("v99").unwrap();
        assert_eq!(code, 2);
    }
}
