//! ORDCHG full pipeline roundtrip tests.
//!
//! Tests EDIFACT -> tokenize -> split -> assemble -> map_interchange("")
//! -> map_interchange_reverse -> disassemble -> render -> byte-identical comparison.
//!
//! All 3 ORDCHG PIDs are message-only (no transaction group).

mod common;

use std::path::Path;

// ── Roundtrip tests (all generated fixtures) ──

fn run_ordchg_pid_roundtrip(pid: &str) {
    let fixture = common::ordchg::discover_generated_fixture(pid)
        .unwrap_or_else(|| panic!("No generated fixture found for ORDCHG PID {pid}"));

    let mig = common::ordchg::load_pid_filtered_mig(pid).unwrap();
    let msg_engine = common::ordchg::load_message_engine();
    let tx_engine = mig_bo4e::engine::MappingEngine::from_definitions(vec![]);

    common::test_utils::run_single_fixture_roundtrip_with_tx_group(
        pid,
        &fixture,
        &mig,
        &msg_engine,
        &tx_engine,
        common::ordchg::TX_GROUP,
    );
}

#[test]
fn test_ordchg_pid_39000_generated_roundtrip() {
    run_ordchg_pid_roundtrip("39000");
}

#[test]
fn test_ordchg_pid_39001_generated_roundtrip() {
    run_ordchg_pid_roundtrip("39001");
}

#[test]
fn test_ordchg_pid_39002_generated_roundtrip() {
    run_ordchg_pid_roundtrip("39002");
}

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

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

    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 = ["39000", "39001", "39002"];

    for pid in pids {
        let tx_dir = common::ordchg::pid_dir(pid);
        if tx_dir.exists() {
            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}"),
            }
        } else {
            eprintln!("PID {pid}: no PID-specific directory (message-only) -- OK");
        }
    }
}

// ── Generated fixture roundtrip tests ──

const ALL_PIDS: &[&str] = &["39000", "39001", "39002"];

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

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

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

        let tx_dir = common::ordchg::pid_dir(pid);
        let (msg_engine, tx_engine) = if tx_dir.exists() {
            common::ordchg::load_split_engines(pid)
        } else {
            let msg = common::ordchg::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::ordchg::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!(
        "\nORDCHG 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
        );
    }
}
