import re, sys

src = open('/tmp/opencode/sample.clean.lua', 'r', encoding='utf-8').read()

# 1. register every prototype table handed to the interpreter factory
needle = "_\u005b0X2a] = function(O, K)"
assert needle in src, "factory site not found"
src = src.replace(needle, needle + "\n\t\t\t\t__P[#__P+1] = { O, _ }", 1)

# 2. wrap the single top-level return in a function so we can pcall and dump
first = src.index('return')
assert src[first:first+7] == 'return '
body = src[first+7:]

harness = r'''
local __P = {}
local __seen = {}
local function __ser(v, depth, out)
  local t = type(v)
  if t == "number" or t == "boolean" or t == "nil" then
    out[#out+1] = tostring(v)
  elseif t == "string" then
    out[#out+1] = string.format("%q", v)
  elseif t == "table" then
    if depth > 3 then out[#out+1] = "{...}" return end
    local parts = {}
    local n = 0
    for k, x in pairs(v) do
      n = n + 1
      if n > 4000 then parts[#parts+1] = "<trunc>" break end
      parts[#parts+1] = "[" .. __ser(k, depth+1, {}) .. "]=" .. __ser(x, depth+1, {})
    end
    out[#out+1] = "{" .. table.concat(parts, ",") .. "}"
  else
    out[#out+1] = "<" .. t .. ">"
  end
  return out[#out] or ""
end
local function __dump()
  print("PROTOCOUNT", #__P)
  for i, rec in ipairs(__P) do
    local O = rec[1]
    io = nil
    local arr = O and O[3]
    print("PROTO", i, "ins", type(arr)=="table" and #arr or -1,
          "O3", type(O[3]), "O4", type(O[4]), "O6", type(O[6]),
          "O7", type(O[7]), "O8", type(O[8]), "O9", type(O[9]),
          "O10", type(O[10]), "O11", type(O[11]))
    if type(arr) == "table" then
      local hist = {}
      for _, q in ipairs(arr) do hist[q] = (hist[q] or 0) + 1 end
      local keys = {}
      for k in pairs(hist) do keys[#keys+1] = k end
      table.sort(keys)
      local hp = {}
      for _, k in ipairs(keys) do hp[#hp+1] = k .. ":" .. hist[k] end
      print("HIST", i, table.concat(hp, " "))
      for slot = 3, 11 do
        local a = O[slot]
        if type(a) == "table" then
          print("ARR", i, slot, #a, __ser(a, 0, {}))
        end
      end
    end
  end
end
local function __main(...)
  return ''' + body + r'''
end
local __ok, __e = pcall(__main, ...)
if not __ok then print("TOPERR", tostring(__e)) end
__dump()
'''

open('/tmp/opencode/sample.trace.luau', 'w', encoding='utf-8').write(harness)
print("wrote", len(harness))
