import os, re, shutil

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

ns = {}
exec(open("/tmp/opencode/patch_connectors.py").read().split("def patch(")[0], ns)
strip_lua = ns["strip_lua"]
OPENERS = ("function", "do", "if", "repeat")
CLOSERS = ("end", "until")

def balance(src):
    d = 0
    for t in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", strip_lua(src)):
        if t in OPENERS: d += 1
        elif t in CLOSERS: d -= 1
    return d

OLD_START = 'task.spawn(LPH_NO_VIRTUALIZE(function()\n    while true do\n        task.wait(0.1)\n        if not Configuration.BronxRelated.Farms.FarmBank then continue end'
OLD_END = 'task.spawn(LPH_NO_VIRTUALIZE(function()\n    while true do\n        task.wait(0.1)\n        if not Configuration.BronxRelated.Farms.FarmTrash then continue end'
UI_ANCHOR = '''            AutoFarm_Section:AddToggle({
                Title = "Farm Studio Robbery",'''
UI_INSERT = '''            AutoFarm_Section:AddToggle({
                Title = "Farm Bank Robbery",
                Flag = "FarmBank/TheBronx",
                Default = false,
                Callback = function(State)
                    Configuration.BronxRelated.Farms.FarmBank = State
                end
            })

            AutoFarm_Section:AddToggle({
                Title = "Farm Studio Robbery",'''

name = "corrupt.lua"
path = os.path.join(BASE, name)
src = open(path, encoding="utf-8", errors="surrogateescape").read()
b0 = balance(src)
a = src.find(OLD_START)
b = src.find(OLD_END)
print("found block:", a, b)
assert a > 0 and b > a
src2 = src[:a] + NEW + "\n" + src[b:]
assert 'Title = "Farm Bank Robbery"' not in src2
assert UI_ANCHOR in src2
src2 = src2.replace(UI_ANCHOR, UI_INSERT, 1)
b1 = balance(src2)
print("%s: balance %d -> %d (delta %d)" % (name, b0, b1, b1 - b0))
assert b1 == b0
if not os.path.exists(path + ".pre-farms.bak"):
    shutil.copy2(path, path + ".pre-farms.bak")
open(path, "w", encoding="utf-8", errors="surrogateescape").write(src2)
print("written:", name)
