import os, shutil

BASE = "/opt/ws-remote/scripts/soleezz/bronx"
NEW = open("/tmp/opencode/new-fovcircle.lua").read()

START = "    FOVCircle = LPH_NO_VIRTUALIZE(function()"
END = "    AimLock = LPH_NO_VIRTUALIZE(function()"

ns = {}
exec(open("/tmp/opencode/patch_connectors.py").read().split("def patch(")[0], ns)
balance = ns["balance"]

path = os.path.join(BASE, "corrupt.lua")
src = open(path, encoding="utf-8", errors="surrogateescape").read()
b0 = balance(src)
a = src.index(START)
b = src.index(END, a)
old = src[a:b]
src2 = src[:a] + NEW + src[b:]

anchor = "getgenv().CorruptCleanup = function()\n"
ins = ('getgenv().CorruptCleanup = function()\n'
       '    pcall(function() RunService:UnbindFromRenderStep("CorruptFovCircle") end)\n')
if anchor in src2 and 'UnbindFromRenderStep("CorruptFovCircle")' not in src2:
    src2 = src2.replace(anchor, ins, 1)

b1 = balance(src2)
print("corrupt.lua balance before=%d after=%d delta=%d old_lines=%d new_lines=%d"
      % (b0, b1, b1 - b0, old.count("\n"), NEW.count("\n")))
if b1 != b0:
    print("!! BALANCE CHANGED - not writing")
    raise SystemExit(1)
if not os.path.exists(path + ".pre-fovcircle.bak"):
    shutil.copy2(path, path + ".pre-fovcircle.bak")
open(path, "w", encoding="utf-8", errors="surrogateescape").write(src2)
print("written")
