import re

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

needle = "_\u005b0X2a]=(function(O,K)"
assert src.count(needle) == 1
src = src.replace(needle, needle + "__P[#__P+1]=O;", 1)

i = src.index('return(')
body = src[i + len('return'):]

pre = r'''local __P={}
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>2 then out[#out+1]="<t>" return out[#out] end
    local parts,n={},0
    for k,x in pairs(v) do
      n=n+1
      if n>2500 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]
    local arr=O and O[3]
    if type(arr)=="table" and #arr>2 then
      print("PROTO",i,"ins",#arr)
      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" and #a>0 then
          print("ARR",i,slot,#a,__ser(a,0,{}))
        end
      end
    end
  end
end
local function __main(...)
  return '''

post = r'''
end
local __ok,__e=pcall(__main,...)
if not __ok then print("TOPERR",tostring(__e)) end
__dump()
'''

out = src[:i] + pre + body + post
open('/tmp/opencode/sample.trace.luau', 'w', encoding='utf-8').write(out)
print("wrote", len(out))
