#!/usr/bin/env python3
"""Run a Lua chunk against roblox_mock.luau with the real uip100 library."""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path

ROOT = Path("/tmp/opencode")
LUAU = ROOT / "luau-src/build/luau"


def lua_long(text: str) -> str:
    for level in range(0, 24):
        eq = "=" * level
        if ("]" + eq + "]") not in text and ("[" + eq + "[") not in text:
            return "[" + eq + "[" + text + "]" + eq + "]"
    raise ValueError("could not bracket text")


def main() -> int:
    if len(sys.argv) < 2:
        print("usage: run_mock.py <chunk.lua> [label]", file=sys.stderr)
        return 2
    chunk_path = Path(sys.argv[1])
    label = sys.argv[2] if len(sys.argv) > 2 else chunk_path.stem
    mock = (ROOT / "roblox_mock.luau").read_text(encoding="utf-8")
    uip = (ROOT / "uip100.lua").read_text(encoding="utf-8", errors="replace")
    chunk = chunk_path.read_text(encoding="utf-8", errors="replace")
    runner = f"""
{mock}
__UIP100 = {lua_long(uip)}
local __chunk = {lua_long(chunk)}
local __fn, __err = loadstring(__chunk)
if not __fn then
    print("LOAD_ERR", tostring(__err))
    return
end
local __ok, __res = pcall(__fn)
print("RUN_RESULT", tostring(__ok), tostring(__res))
local __vis = getgenv().OpOneVISCHECK
if __vis and __vis.recolor then
    local ok, err = pcall(function()
        __vis.recolor(Color3.fromRGB(1, 2, 3), Color3.fromRGB(4, 5, 6))
    end)
    print("RECOLOR", tostring(ok), tostring(err))
end
local __render = getgenv().OpOneDebug
if __render then print("DEBUG_READY", typeof(__render)) end
local ok, err = pcall(M.fire_render)
print("RENDER", tostring(ok), tostring(err))
"""
    out = ROOT / f"mock_run_{label}.lua"
    out.write_text(runner, encoding="utf-8")
    proc = subprocess.run([str(LUAU), str(out)], capture_output=True, timeout=120)
    text = proc.stdout.decode("utf-8", "replace")
    err = proc.stderr.decode("utf-8", "replace")
    print(text)
    if err:
        print("STDERR:", err)
    print("RC", proc.returncode)
    return proc.returncode


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