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("%q", x:sub(1, 40)) end
  if t == "number" then return string.format("%.10g", x) end
  if t == "table" then return "tbl#" .. tostring(#x) end
  if t == "function" then return "fn" end
  return t .. ":" .. tostring(x)
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
__DUMPED = false
__CALL140 = 0
__OPN = 0
__LASTO = nil
__LASTPC = 0
function __OP(O, pc, z, a, b, c, d, e, f, regs)
  __OPN = __OPN + 1
  local ni = __nins(O)
  if O ~= __LASTO then
    if ni == 140 and not __DUMPED then
      __DUMPED = true
      __realprint("D140", tostring(O))
      for i = 1, 140 do
        __realprint("I", i, "op", __V(__g(O,3)[i]), "t", __V(__g(O,4)[i]), "d", __V(__g(O,5)[i]), "P", __V(__g(O,10)[i]), "b", __V(__g(O,7)[i]), "y", __V(__g(O,9)[i]), "p", __V(__g(O,8)[i]))
      end
    end
    if ni == 140 and pc == 1 then
      __CALL140 = __CALL140 + 1
      if __CALL140 <= 3 then
        local parts = {}
        for k = 1, 12 do parts[#parts+1] = k .. "=" .. __V(regs[k]) end
        __realprint("CALL140", __CALL140, table.concat(parts, " "))
      end
    end
    __LASTO = O
  end
  __LASTPC = pc
end
'''

old = '''    __index = function(self, k)
      if k == "ClassName" then return "Proxy" end'''
new = '''    __index = function(self, k)
      if __PLOG then __PLOG(name, k) end
      if k == "ClassName" then return "Proxy" end'''
shim = shim.replace(old, new, 1)
shim = shim.replace('__PLOGN = 0', '__PLOGN = 0', 1)
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,t[Q],d[Q],P[Q],y[Q],b[Q],p[Q],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/probe9.luau','w').write(shim + tail)
print("wrote")
