import re

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

extra = r'''
__G3N = 0
function __G3(k, v)
  if __G3N < 3000 then
    __G3N = __G3N + 1
    local vt = type(v)
    local vs
    if vt == "string" then vs = string.format("%q", v:sub(1, 60))
    elseif vt == "number" or vt == "boolean" or vt == "nil" then vs = tostring(v)
    elseif vt == "table" then
      local ok, n = pcall(function() local z = 0 for _ in pairs(v) do z = z + 1 end return z end)
      vs = "table#" .. tostring(ok and n or "?")
    else vs = vt end
    __realprint("G3", tostring(k), vt, vs)
  end
end
__PLOGN = 0
function __PLOG(name, k)
  if __PLOGN < 1000 then
    __PLOGN = __PLOGN + 1
    __realprint("PROXY", tostring(name), tostring(k))
  end
end

function __V(x)
  local t = type(x)
  if t == "string" then return string.format("%q", x:sub(1, 50)) end
  if t == "number" then return string.format("%.10g", x) end
  if t == "table" then return "tbl#" .. tostring(#x) end
  return t .. ":" .. tostring(x)
end
function __DUMPPROTO(O)
  __realprint("DUMPPROTO", tostring(O), "n", #O[3])
  for pc = 1, 60 do
    __realprint("PCD", pc, "op", __V(O[3][pc]), "A", __V(O[4][pc]), "B", __V(O[5][pc]), "C", __V(O[6][pc]), "D", __V(O[7][pc]), "E", __V(O[8][pc]), "F", __V(O[9][pc]), "G", __V(O[10][pc]), "H", __V(O[11][pc]))
  end
end

__OPN = 0
__OPCNT = {}
__LAST = {}
__LASTN = 0
function __OP(O, q, z)
  __OPN = __OPN + 1
  local c = __OPCNT[O]
  if not c then c = {}; __OPCNT[O] = c end
  local key = q * 65536 + z
  c[key] = (c[key] or 0) + 1
  __LASTN = __LASTN + 1
  local idx = (__LASTN % 64) + 1
  __LAST[idx] = tostring(O) .. ":" .. tostring(q) .. ":" .. tostring(z)
  if __OPN % 2000000 == 0 then
    __realprint("WATCH", __OPN)
    local all = {}
    for OO, cc in pairs(__OPCNT) do
      for k, n in pairs(cc) do all[#all+1] = {OO, k, n} end
    end
    table.sort(all, function(a, b) return a[3] > b[3] end)
    for i = 1, math.min(12, #all) do
      local OO, k, n = all[i][1], all[i][2], all[i][3]
      local pc = math.floor(k / 65536)
      local zz = k % 65536
      __realprint("TOP", tostring(OO), "pc", pc, "op", zz, "n", n)
    end
    if not __DUMPED and #all > 0 then
      __DUMPED = true
      __DUMPPROTO(all[1][1])
    end
  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)

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);', 1)

s = s.replace('return({', 'local __T={', 1)
s = s.rstrip()[:-len('}):A();')] + '};__WRAP(__T);return __T:A();'

profile = r'''
local __CNT = {}
local __CALLS = 0
function __WRAP(T)
  for k, v in pairs(T) do
    if type(v) == "function" then
      __CNT[k] = 0
      T[k] = function(...)
        __CNT[k] = __CNT[k] + 1
        __CALLS = __CALLS + 1
        return v(...)
      end
    end
  end
end
'''

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))
  local ks = {}
  for k, n in pairs(__CNT) do ks[#ks+1] = k end
  table.sort(ks, function(a, b) return __CNT[a] > __CNT[b] end)
  __realprint("CALLS", __CALLS, "OPS", __OPN, "DISTINCT", __OPDISTINCT)
  for i = 1, math.min(#ks, 20) do __realprint("HOT", ks[i], __CNT[ks[i]]) end
end
'''
out = shim + profile + tail
open('/tmp/opencode/probe5.luau', 'w').write(out)
print("wrote", len(out))
