import subprocess, sys, tempfile, time, statistics, os
from pathlib import Path
BENCH = '''
local s = 0
for i = 1, 2000000 do s = s + i % 7 end
local t = {}
for i = 1, 200000 do t[i] = i * 2 end
local x = 0
for i = 1, 200000 do x = x + t[i] end
local function f(a, b) return a * b + a - b end
local y = 0
for i = 1, 300000 do y = y + f(i, 3) end
print(s, x, y)
'''
LUAU = '/tmp/opencode/luau-src/build/luau'
def build(root, src, out):
    sys.path.insert(0, root + '/luraph_compiler')
    for m in list(sys.modules):
        if m in ('compiler','isa','luau_bc','macros','handler_runtime'):
            del sys.modules[m]
    import compiler
    t0=time.time()
    text=compiler.compile_source(src, key=7, hardened=True, binary=True)
    dt=time.time()-t0
    Path(out).write_text(text)
    return dt, len(text)

with tempfile.TemporaryDirectory() as td:
    src=Path(td)/'b.luau'; src.write_text(BENCH)
    direct=[]
    for _ in range(3):
        t0=time.perf_counter(); r=subprocess.run([LUAU,str(src)],capture_output=True,text=True); direct.append(time.perf_counter()-t0)
    print('native', round(statistics.median(direct),3), r.stdout.strip())
    for name,root in [('baseline','/tmp/opencode/obf_work/baseline'),('agent2','/tmp/opencode/obf_work/agent2')]:
        out=Path(td)/(name+'.luau')
        cdt, size = build(root, BENCH, out)
        ts=[]
        for _ in range(3):
            t0=time.perf_counter(); r=subprocess.run([LUAU,str(out)],capture_output=True,text=True,timeout=300); ts.append(time.perf_counter()-t0)
        print(name, 'bytes', size, 'compile', round(cdt,2), 'run', round(statistics.median(ts),3), r.stdout.strip(), r.stderr[-120:])
