"""The ultimate regression test: the actual production PumpController*.mbs
scripts, compiled and compared byte-for-byte against their real RoborunPlus
.hex output.

Unlike tests/fixtures/ (small, single-purpose minimal-pair test programs
built specifically to pin down individual opcodes), these are real-world
scripts nobody wrote for reverse-engineering purposes -- they're what this
compiler actually needs to produce correctly. A failure here means the
compiler cannot yet be trusted on real hardware, regardless of how the
synthetic corpus looks.
"""

from pathlib import Path

import pytest

from microbasic_compiler.codegen import generate_bytecode
from microbasic_compiler.hexfile import read_intel_hex
from microbasic_compiler.lexer import tokenize
from microbasic_compiler.parser import parse
from microbasic_compiler.preprocessor import expand_macros

REAL_SCRIPTS_DIR = Path(__file__).parent / "real_scripts"
SCRIPT_NAMES = sorted(p.stem for p in REAL_SCRIPTS_DIR.glob("*.mbs"))


@pytest.mark.parametrize("name", SCRIPT_NAMES)
def test_real_script_matches_real_compiler_output(name: str):
    source = (REAL_SCRIPTS_DIR / f"{name}.mbs").read_text()
    expected = read_intel_hex((REAL_SCRIPTS_DIR / f"{name}.hex").read_text()).rstrip(b"\xff")
    tokens = expand_macros(tokenize(source))
    program = parse(tokens)
    actual = generate_bytecode(program)
    assert actual == expected, (
        f"{name}: compiled output does not match real RoborunPlus .hex "
        f"(actual {len(actual)} bytes, expected {len(expected)} bytes)"
    )
