//! MSCONS full pipeline roundtrip tests.
//!
//! Tests EDIFACT → tokenize → split → assemble → map_interchange(SG5)
//! → map_interchange_reverse → disassemble → render → byte-identical comparison.

mod common;

const ALL_PIDS: &[&str] = &[
    "13002", "13003", "13005", "13006", "13007", "13008", "13009", "13010", "13011", "13012",
    "13013", "13014", "13015", "13016", "13017", "13018", "13019", "13020", "13021", "13022",
    "13023", "13024", "13025", "13026", "13027", "13028",
];

/// PIDs with known mapping gaps that prevent byte-identical roundtrip.
/// Empty = all PIDs pass. Add PIDs here when new schema segments are discovered
/// that need mapping work.
const KNOWN_INCOMPLETE: &[&str] = &[];

// ── Real fixture roundtrip tests ──

#[test]
fn test_mscons_pid_13017_roundtrip() {
    common::mscons::run_full_roundtrip("13017");
}

// ── Generated fixture roundtrip tests ──
//
// These test against generated fixtures that exercise the full PID schema
// (including QTY unit codes, all DTM variants, and STS status segments).
// PIDs listed in KNOWN_INCOMPLETE are expected to fail due to mapping gaps.

#[test]
fn test_mscons_generated_roundtrip_all() {
    let mut passed = 0;
    let mut failed = Vec::new();
    let mut skipped = 0;

    for pid in ALL_PIDS {
        let Some(fixture) = common::mscons::discover_generated_fixture(pid) else {
            eprintln!("PID {pid}: no generated fixture — skipping");
            skipped += 1;
            continue;
        };

        let Some(mig) = common::mscons::load_pid_filtered_mig(pid) else {
            eprintln!("PID {pid}: MIG/AHB XML not available — skipping");
            skipped += 1;
            continue;
        };

        let (msg_engine, tx_engine) = common::mscons::load_split_engines(pid);

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            common::test_utils::run_single_fixture_roundtrip_with_tx_group(
                pid,
                &fixture,
                &mig,
                &msg_engine,
                &tx_engine,
                common::mscons::TX_GROUP,
            );
        }));

        match result {
            Ok(()) => {
                if KNOWN_INCOMPLETE.contains(pid) {
                    eprintln!(
                        "PID {pid}: PASSED (was KNOWN_INCOMPLETE — can be removed from list!)"
                    );
                }
                passed += 1;
            }
            Err(_) => {
                if KNOWN_INCOMPLETE.contains(pid) {
                    eprintln!("PID {pid}: KNOWN_INCOMPLETE (expected failure)");
                } else {
                    eprintln!("PID {pid}: UNEXPECTED FAILURE");
                    failed.push(*pid);
                }
            }
        }
    }

    eprintln!(
        "\nMSCONS generated roundtrip: {passed} passed, {} known incomplete, {skipped} skipped",
        KNOWN_INCOMPLETE.len()
    );

    if !failed.is_empty() {
        panic!(
            "Unexpected failures for PIDs: {:?} — add to KNOWN_INCOMPLETE or fix mappings",
            failed
        );
    }
}

// ── TOML loading test ──

/// Verify all MSCONS PID TOML mappings load successfully.
#[test]
fn test_mscons_all_pids_toml_loading() {
    use mig_bo4e::engine::MappingEngine;
    use mig_bo4e::path_resolver::PathResolver;
    use std::path::Path;

    let schema_dir = Path::new(common::mscons::SCHEMA_DIR);
    let msg_dir = common::mscons::message_dir();
    let resolver = PathResolver::from_schema_dir(schema_dir);

    // Verify message-level engine loads
    let msg_engine = MappingEngine::load(&msg_dir)
        .unwrap()
        .with_path_resolver(resolver.clone());
    assert!(
        !msg_engine.definitions().is_empty(),
        "Message engine should have definitions"
    );

    // Verify each PID's transaction engine loads
    for pid in ALL_PIDS {
        let tx_dir = common::mscons::pid_dir(pid);
        if !tx_dir.exists() {
            eprintln!("PID {pid}: no mapping directory — skipping");
            continue;
        }

        let cmn_dir = common::mscons::common_dir();
        if cmn_dir.exists() {
            let idx = common::mscons::schema_index(pid);
            let result = MappingEngine::load_with_common(&cmn_dir, &tx_dir, &idx);
            match result {
                Ok(engine) => {
                    let engine = engine.with_path_resolver(resolver.clone());
                    let count = engine.definitions().len();
                    eprintln!("PID {pid}: {count} definitions loaded OK");
                }
                Err(e) => panic!("PID {pid}: failed to load TOML mappings: {e}"),
            }
        } else {
            match MappingEngine::load(&tx_dir) {
                Ok(engine) => {
                    let engine = engine.with_path_resolver(resolver.clone());
                    let count = engine.definitions().len();
                    eprintln!("PID {pid}: {count} definitions loaded OK");
                }
                Err(e) => panic!("PID {pid}: failed to load TOML mappings: {e}"),
            }
        }
    }
}
