import re

SRC = open('/tmp/opencode/make_runner.py').read()
shim = re.search(r"shim = r'''(.*?)'''", SRC, re.S).group(1)

extra = r'''
function __V(x)
  local t=type(x)
  if t=="string" then return string.format("str#%d",#x)
  elseif t=="number" then return string.format("%.10g",x)
  elseif t=="table" then local n=0 for _ in pairs(x) do n=n+1 if n>2000 then break end end return "tbl#"..#x.."/"..n
  elseif t=="function" then return "fn" end
  return t
end
local function __g(t,k) local ok,v=pcall(function() return t[k] end); if ok then return v end return nil end
__NINS={}
local function __nins(O) local n=__NINS[O]; if n then return n end; local o3=__g(O,3); if type(o3)=="table" then n=#o3 else n=-1 end; __NINS[O]=n; return n end
__OPS=0 __ITERS=0 __PHASE2=false
function __OP(O,pc,z,regs)
  __OPS=__OPS+1
  local n=__nins(O)
  if n==140 then
    if pc==8 then
      __ITERS=__ITERS+1
      if type(regs[9])=="number" and regs[9]>=255 then __PHASE2=true end
    end
    if __PHASE2 and __OPS % 500000 == 0 then
      local p={} for i=1,18 do p[#p+1]=i.."="..__V(regs[i]) end
      __realprint("S", __OPS, "pc", pc, table.concat(p," "))
    end
  end
  if __OPS % 500000 == 0 then
    __realprint("G", __OPS, "cur", n, "pc", pc, "phase2", tostring(__PHASE2))
  end
end
'''

shim += extra

raw = open('/tmp/opencode/stage2.lua').read()
rhex = re.search(r'__RHEX__\t([0-9a-f]+)', open('/tmp/opencode/cap4.txt').read()).group(1)
rbytes = bytes.fromhex(rhex)
rlit = '"' + ''.join('\\x%02x' % b for b in rbytes) + '"'

s = raw
s = 'local R=buffer.fromstring(' + rlit + ');' + s[len('local R=...;'):]
head = 'while true do local Z=o[Q];'
assert s.count(head) == 1
s = s.replace(head, 'while true do local Z=o[Q];__OP(O,Q,Z,q);', 1)

tail = r'''
local __ok,__err = pcall(function()
''' + s + r'''
end)
__realprint("EXEC1", __ok, type(__err))
if __ok then
  local __ok2,__err2 = pcall(__err)
  __realprint("EXEC2", __ok2, tostring(__err2))
end
'''
open('/tmp/opencode/probe_p2state.luau','w').write(shim + tail)
print("wrote")
