//! COMDIS full pipeline roundtrip tests.
//!
//! Tests EDIFACT -> tokenize -> split -> assemble -> map_interchange(SG2)
//! -> map_interchange_reverse -> disassemble -> render -> byte-identical comparison.

mod common;

use std::path::Path;

// ── Roundtrip tests ──

#[test]
fn test_comdis_pid_29001_roundtrip() {
    common::comdis::run_full_roundtrip("29001");
}

#[test]
fn test_comdis_pid_29001_generated_roundtrip() {
    let fixture = common::comdis::discover_generated_fixture("29001")
        .expect("Generated fixture not found for PID 29001");

    let mig = common::comdis::load_pid_filtered_mig("29001").unwrap();
    let (msg_engine, tx_engine) = common::comdis::load_split_engines("29001");

    common::test_utils::run_single_fixture_roundtrip_with_tx_group(
        "29001",
        &fixture,
        &mig,
        &msg_engine,
        &tx_engine,
        common::comdis::TX_GROUP,
    );
}

#[test]
fn test_comdis_pid_29002_generated_roundtrip() {
    let fixture = common::comdis::discover_generated_fixture("29002")
        .expect("Generated fixture not found for PID 29002");

    let mig = common::comdis::load_pid_filtered_mig("29002").unwrap();
    let (msg_engine, tx_engine) = common::comdis::load_split_engines("29002");

    common::test_utils::run_single_fixture_roundtrip_with_tx_group(
        "29002",
        &fixture,
        &mig,
        &msg_engine,
        &tx_engine,
        common::comdis::TX_GROUP,
    );
}

/// Verify all COMDIS PID TOML mappings load successfully.
#[test]
fn test_comdis_all_pids_toml_loading() {
    use mig_bo4e::engine::MappingEngine;
    use mig_bo4e::path_resolver::PathResolver;

    let schema_dir = Path::new(common::comdis::SCHEMA_DIR);
    let msg_dir = common::comdis::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"
    );

    let pids = ["29001", "29002"];

    for pid in pids {
        let tx_dir = common::comdis::pid_dir(pid);
        if !tx_dir.exists() {
            eprintln!("PID {pid}: no mapping directory -- skipping");
            continue;
        }

        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}"),
        }
    }
}

// ── Generated fixture roundtrip tests ──

const ALL_PIDS: &[&str] = &["29001", "29002"];

/// PIDs with known mapping gaps that prevent byte-identical roundtrip.
const KNOWN_INCOMPLETE: &[&str] = &[];

#[test]
fn test_comdis_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::comdis::discover_generated_fixture(pid) else {
            eprintln!("PID {pid}: no generated fixture — skipping");
            skipped += 1;
            continue;
        };

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

        let tx_dir = common::comdis::pid_dir(pid);
        let (msg_engine, tx_engine) = if tx_dir.exists() {
            common::comdis::load_split_engines(pid)
        } else {
            let msg = common::comdis::load_message_engine();
            let tx = mig_bo4e::engine::MappingEngine::from_definitions(vec![]);
            (msg, tx)
        };

        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::comdis::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!(
        "\nCOMDIS 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
        );
    }
}
