import sys, tempfile, subprocess
from pathlib import Path
sys.path.insert(0, '/tmp/opencode/obf_work/agent2/luraph_compiler')
import compiler
LUAU = compiler.LUAU
CASES = {
'control': '''
local s = 0
for i = 1, 20 do
  if i % 3 == 0 then continue end
  for j = 1, 5 do
    if j == 4 then break end
    s = s + i * j
  end
end
local k = 0
while true do k = k + 1 if k >= 7 then break end end
repeat k = k - 1 until k <= 0
print(s, k)
''',
'errloop': '''
local function f(n)
  local s = 0
  for i = 1, n do
    s = s + i
    if i == 3 then error("stop" .. i) end
  end
  return s
end
for t = 1, 3 do
  local ok, e = pcall(f, 5)
  print(ok, tostring(e):match("stop3") ~= nil)
end
print(pcall(f, 2))
''',
'closure_loop': '''
local fns = {}
for i = 1, 5 do
  local x = i * 10
  fns[i] = function() x = x + 1 return x end
end
local a = fns[1]()
local b = fns[1]()
local c = fns[3]()
print(a, b, c)
''',
'metatable': '''
local mt = {__index = function(t, k) return k .. "!" end, __add = function(a, b) return a.v + b.v end}
local a = setmetatable({v = 2}, mt)
local b = setmetatable({v = 5}, mt)
print(a.missing, a + b)
for i = 1, 6 do a["k" .. i] = i end
local n = 0
for k, v in pairs(a) do if type(v) == "number" then n = n + v end end
print(n)
''',
'multiret': '''
local function f(x)
  if x < 0 then return end
  if x == 0 then return 0, "zero" end
  local a, b = 1, 1
  for i = 1, x do a, b = b, a + b end
  return a, b, a + b
end
print(f(-1))
print(f(0))
print(f(8))
local t = {f(5)}
print(#t, table.concat(t, ","))
''',
'vararg_deep': '''
local function pack2(...)
  local n = select("#", ...)
  local out = {}
  for i = 1, n do
    local v = select(i, ...)
    out[i] = type(v) .. ":" .. tostring(v)
  end
  return n, table.concat(out, "|")
end
local function relay(...) return pack2(...) end
print(relay(1, "a", true, nil, 2.5))
print(relay())
''',
}
fails=0
for key in range(1, 21):
    for name, src in 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: print('skip',name,r.stderr[-100:]); continue
            p=td/'p.luau'
            try: p.write_text(compiler.compile_source(src,key=key,hardened=True,binary=True))
            except Exception as e: print('CF',key,name,e); fails+=1; continue
            r2=subprocess.run([LUAU,str(p)],capture_output=True,text=True,timeout=120)
            if r2.returncode or r2.stdout!=r.stdout:
                print('FAIL',key,name,repr(r.stdout),repr(r2.stdout),r2.stderr[-300:]); fails+=1
print('fails',fails)
sys.exit(1 if fails else 0)
