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()"

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

def patch(name):
    path = os.path.join(BASE, name)
    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]
    if "Accum < 0.033" not in old:
        print("  (no accumulator found in", name, "block - aborting)")
        return False
    src2 = src[:a] + NEW + src[b:]

    # unbind the FOV circle render step on cleanup
    cfg = '        RunService:UnbindFromRenderStep("CorruptFovSync")'
    if cfg in src2 and 'UnbindFromRenderStep("CorruptFovCircle")' not in src2:
        src2 = src2.replace(
            cfg,
            '        RunService:UnbindFromRenderStep("CorruptFovSync")\n'
            '        RunService:UnbindFromRenderStep("CorruptFovCircle")',
            1,
        )

    b1 = balance(src2)
    print("%-24s balance before=%d after=%d delta=%d  old_lines=%d new_lines=%d"
          % (name, b0, b1, b1 - b0, old.count("\n"), NEW.count("\n")))
    if b1 != b0:
        print("  !! BALANCE CHANGED - not writing", name)
        return False
    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)
    return True

for f in ("corrupt.lua", "corrupt-optimized.lua"):
    patch(f)
