import re

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

extra = r'''
__SKIP42 = setmetatable({}, {
  __index = function(t, k)
    local v = string[k]
    if v ~= nil then return v end
    return function() return 0 end
  end,
  __mul = function() return 0 end,
  __add = function() return 0 end,
  __sub = function() return 0 end,
  __div = function() return 0 end,
  __mod = function() return 0 end,
  __unm = function() return 0 end,
  __tostring = function() return "stub42" end,
})
__I = 0
function __G3(k, v)
  __I = __I + 1
  if __I <= 800 then
    local vt = type(v)
    local vs = vt == "string" and string.format("%q", v:sub(1, 60)) or tostring(v)
    __realprint("G3", tostring(k), vt, vs)
  end
end
__PLOGN = 0
function __PLOG(name, k)
  if __PLOGN < 800 then
    __PLOGN = __PLOGN + 1
    __realprint("PROXY", tostring(name), tostring(k))
  end
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 += 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=...;'):]

get = '(q)[d[Q]]=S[p[Q]];'
assert s.count(get) == 1
s = s.replace(get, '  local __sv=S[p[Q]];__G3(p[Q],__sv);(q)[d[Q]]=__sv;', 1)

ret = 'return h;end;if not T[13084]'
assert s.count(ret) == 1
stub = 'if type(O)=="table" and type(O[3])=="table" and #O[3]==42 then __realprint("STUBMAKE140", tostring(O)); return function() return __SKIP42 end end;'
s = s.replace(ret, stub + ret, 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/probe16.luau','w').write(shim + tail)
print("wrote")
