import os

ITERATE_PATH = r"C:\kalshibot\Automated\tracker\iterate.py"

with open(ITERATE_PATH, encoding="utf-8") as f:
    lines = f.readlines()

# Find the restart_bot function boundaries
start_idx = None
end_idx = None
for i, line in enumerate(lines):
    if line.strip() == "def restart_bot():":
        start_idx = i - 1  # include the comment line before
        break

if start_idx is None:
    print("ERROR: restart_bot not found")
    exit(1)

# Find end: next top-level def or comment section after restart_bot
for i in range(start_idx + 2, len(lines)):
    if lines[i].startswith("# ──") or (lines[i].startswith("def ") and i > start_idx + 5):
        end_idx = i
        break

print(f"restart_bot: lines {start_idx+1} to {end_idx}")

new_func = '''# -- Kill and restart bot -------------------------------------------------------
def restart_bot():
    log("Killing existing Automated bot process...")
    PID_FILE = r"C:\\kalshibot\\Automated\\bot.pid"

    # Kill by saved PID - surgically precise
    killed = False
    if os.path.exists(PID_FILE):
        try:
            with open(PID_FILE) as pf:
                old_pid = int(pf.read().strip())
            result = subprocess.run(
                ["taskkill", "/F", "/PID", str(old_pid)],
                capture_output=True, timeout=10
            )
            log(f"Killed PID {old_pid}: exit={result.returncode}")
            killed = True
        except Exception as e:
            log(f"PID kill failed: {e}")
        finally:
            try:
                os.remove(PID_FILE)
            except:
                pass

    # Fallback: WMI kill by commandline
    if not killed:
        kill_cmd = [
            "powershell", "-Command",
            "Get-WmiObject Win32_Process | Where-Object { .CommandLine -like \'*Automated*paper_trade*\' } | ForEach-Object { Stop-Process -Id .ProcessId -Force -ErrorAction SilentlyContinue }"
        ]
        subprocess.run(kill_cmd, capture_output=True, timeout=15)

    time.sleep(3)

    log("Starting new Automated bot...")
    subprocess.Popen(
        [\'cmd\', \'/k\',
         \'title Kalshibot-Automated && cd /d C:\\\\kalshibot\\\\Automated && python paper_trade.py\'],
        creationflags=subprocess.CREATE_NEW_CONSOLE
    )
    time.sleep(8)

    # Verify it started
    state = load(BOT_STATE_PATH, {})
    if state.get("btc_price", 0) > 0:
        log(f"Bot restarted. BTC={state[\'btc_price\']} Balance=")
        return True
    else:
        log("WARNING: Bot may not have started correctly (no BTC price yet)")
        return False

'''

new_lines = lines[:start_idx] + [new_func] + lines[end_idx:]

with open(ITERATE_PATH, "w", encoding="utf-8") as f:
    f.writelines(new_lines)

print(f"Done. Wrote {len(new_lines)} lines.")
print("Checking for PID_FILE...")
with open(ITERATE_PATH, encoding="utf-8") as f:
    c = f.read()
print("PID_FILE found:", "PID_FILE" in c)
