//! Byte-equivalence tests for the deterministic Stage 1 files (contexts,
//! mutations, functions, index). Baseline output captured from the JS
//! codegen at `protocol/mizan-generate/generator/lib/stage1.mjs` against
//! the AFI fixture schema (`tests/fixtures/afi_ir.kdl`).
//!
//! `types.ts` is NOT byte-checked here — the JS codegen routes type
//! emission through openapi-typescript while the Rust substrate emits
//! Pydantic schemas directly. Equivalence for types.ts is structural
//! (named exports present and importable), checked in a separate test.

use std::collections::BTreeMap;
use std::path::PathBuf;

use mizan_codegen::config::{Config, SourceConfig};
use mizan_codegen::emit::{CodegenTarget, EmittedFile};
use mizan_codegen::emit::stage1::Stage1;
use mizan_codegen::fetch::parse_ir_from_str;


fn load_ir() -> mizan_codegen::ir::MizanIR {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/afi_ir.kdl");
    let raw = std::fs::read_to_string(&path).unwrap();
    parse_ir_from_str(&raw).unwrap()
}


fn synthetic_config() -> Config {
    Config {
        project_id: None,
        output: PathBuf::from("/tmp"),
        targets: vec!["stage1".to_string()],
        source: SourceConfig { fastapi: None, django: None, rust: None, script: None },
        rust_kernel: None,
        rust_crate_name: None,
    }
}


fn emit_index(files: &[EmittedFile]) -> BTreeMap<PathBuf, &str> {
    files.iter().map(|f| (f.rel_path.clone(), f.content.as_str())).collect()
}


fn read_baseline(rel: &str) -> String {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/baselines/stage1")
        .join(rel);
    std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("read baseline {}: {e}", path.display()))
}


fn assert_byte_equal(rel: &str, files: &BTreeMap<PathBuf, &str>) {
    let actual = files
        .get(&PathBuf::from(rel))
        .unwrap_or_else(|| panic!("emitter did not produce {rel}"));
    let expected = read_baseline(rel);
    if *actual != expected {
        // Surface a diff-friendly failure message — first divergent line wins.
        for (lineno, (a, b)) in actual.lines().zip(expected.lines()).enumerate() {
            if a != b {
                panic!(
                    "{rel} diverges at line {}:\n  expected: {b:?}\n  actual:   {a:?}",
                    lineno + 1,
                );
            }
        }
        panic!(
            "{rel} diverges in length: actual={} expected={}",
            actual.len(), expected.len(),
        );
    }
}


#[test]
fn stage1_contexts_user_byte_match() {
    let ir = load_ir();
    let files = Stage1.emit(&ir, &synthetic_config());
    let index = emit_index(&files);
    assert_byte_equal("contexts/user.ts", &index);
}


#[test]
fn stage1_function_files_byte_match() {
    let ir = load_ir();
    let files = Stage1.emit(&ir, &synthetic_config());
    let index = emit_index(&files);
    for rel in ["functions/echo.ts", "functions/whoami.ts",
                "functions/findUser.ts", "functions/renameUser.ts"] {
        assert_byte_equal(rel, &index);
    }
}


#[test]
fn stage1_mutation_files_byte_match() {
    let ir = load_ir();
    let files = Stage1.emit(&ir, &synthetic_config());
    let index = emit_index(&files);
    assert_byte_equal("mutations/updateProfile.ts", &index);
}


#[test]
fn stage1_index_byte_match() {
    let ir = load_ir();
    let files = Stage1.emit(&ir, &synthetic_config());
    let index = emit_index(&files);
    assert_byte_equal("index.ts", &index);
}


#[test]
fn stage1_types_exports_expected_names() {
    let ir = load_ir();
    let files = Stage1.emit(&ir, &synthetic_config());
    let index = emit_index(&files);
    let types = index
        .get(&PathBuf::from("types.ts"))
        .expect("types.ts must be emitted");

    // Every Pydantic schema named in the IR must surface as a top-level
    // exported type or interface so Stage 2 adapters can import by name.
    for expected in [
        "echoInput", "echoOutput",
        "whoamiOutput",
        "userProfileInput", "userProfileOutput",
        "userOrdersInput",
        "updateProfileInput", "updateProfileOutput",
        "findUserInput", "findUserOutput",
        "renameUserInput", "renameUserOutput",
    ] {
        let needle_interface = format!("export interface {expected} ");
        let needle_type = format!("export type {expected} =");
        assert!(
            types.contains(&needle_interface) || types.contains(&needle_type),
            "types.ts must export {expected:?} (interface or type)",
        );
    }
}
