import os, 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)
balance = ns["balance"]

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",'''

def patch(name):
    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)
    if a < 0 or b < 0 or b <= a:
        print("  %s: farm loop block not found (a=%d b=%d)" % (name, a, b))
        return False
    old = src[a:b]
    src2 = src[:a] + NEW + "\n" + src[b:]

    if 'Title = "Farm Bank Robbery"' not in src2:
        if UI_ANCHOR in src2:
            src2 = src2.replace(UI_ANCHOR, UI_INSERT, 1)
        else:
            print("  %s: UI anchor not found" % name)
            return False

    b1 = balance(src2)
    print("%-24s balance %d -> %d (delta %d) | replaced %d lines with %d | bank toggle added"
          % (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-farms.bak"):
        shutil.copy2(path, path + ".pre-farms.bak")
    open(path, "w", encoding="utf-8", errors="surrogateescape").write(src2)
    return True

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