#!/usr/bin/env python3
"""Regression tests for Secro no-virtualize macros."""
import subprocess
import tempfile
from pathlib import Path
import compiler

LUAU = Path('/tmp/opencode/luau-src/build/luau')
if not LUAU.is_file():
    LUAU = Path('/opt/ws-remote/bin/luau')


def run(source: str, expect: str):
    with tempfile.TemporaryDirectory() as td:
        src = Path(td) / 'input.luau'
        out = Path(td) / 'out.lua'
        src.write_text(source)
        out.write_text(compiler.compile_source(source, key=11, hardened=True, binary=True))
        proc = subprocess.run([str(LUAU), str(out)], capture_output=True, text=True, timeout=60)
        got = (proc.stdout + proc.stderr).strip()
        ok = expect in got and proc.returncode == 0
        print('ok  ' if ok else 'FAIL', expect, '|', got[-120:])
        return ok


def main():
    tests = [
        ('local x=4\nlocal f=SECRO_NO_VIRTUALIZE(function(a) return a+x end)\nprint("N1", f(3))', 'N1\t7'),
        ('local x=2\nlocal f=LPH_NO_VIRTUALIZE(function(a) return a*x end)\nprint("N2", f(5))', 'N2\t10'),
        ('local x=2\nlocal f=SECRO_NO_VIRTUALIZE(function(a) local g=SECRO_NO_VIRTUALIZE(function() return x+a end) return g() end)\nprint("N3", f(5))', 'N3\t7'),
        ('local x=4\nlocal f=SECRO_NO_VIRTUALIZE(function(a) x=x+a return x end)\nprint("N4", f(3), x)', 'N4\t7\t7'),
    ]
    good = sum(run(src, want) for src, want in tests)
    print(f'{good}/{len(tests)} passed')
    return 0 if good == len(tests) else 1


if __name__ == '__main__':
    raise SystemExit(main())
