import sys, tempfile, subprocess
from pathlib import Path
sys.path.insert(0, '/tmp/opencode/obf_work/agent2/luraph_compiler')
import compiler
import test_binary

LUAU = compiler.LUAU
fails = 0
total = 0
for key in range(1, 13):
    for name, src in test_binary.CASES.items():
        with tempfile.TemporaryDirectory() as td:
            td = Path(td)
            d = td / 'd.luau'; d.write_text(src)
            r = subprocess.run([LUAU, str(d)], capture_output=True, text=True, timeout=60)
            if r.returncode != 0:
                continue
            p = td / 'p.luau'
            try:
                p.write_text(compiler.compile_source(src, key=key, hardened=True, binary=True))
            except Exception as e:
                print('COMPILEFAIL', key, name, e); fails += 1; continue
            r2 = subprocess.run([LUAU, str(p)], capture_output=True, text=True, timeout=60)
            total += 1
            if r2.returncode != 0 or r2.stdout != r.stdout:
                fails += 1
                print('FAIL', key, name, r2.returncode, repr(r.stdout), repr(r2.stdout), r2.stderr[-200:])
print('total', total, 'fails', fails)
sys.exit(1 if fails else 0)
