# -*- coding: utf-8 -*-
"""fix-launcher-proxy.py —— 工作电脑：把启动脚本里的全局代理拆掉，只留 TG 的显式代理
规则（老板 2026-09-30 硬要求）：模型必须直连（大陆 IP），只有 Telegram 走代理。
做法：删 HTTP_PROXY / HTTPS_PROXY / ALL_PROXY 三行，保留/补 TELEGRAM_PROXY，
      NO_PROXY 留着（对其他工具无害）。
"""
import argparse
import os
import shutil
import sys
import time

BAT_CANDS = [
    r"D:\soft\hermes\run_hermes.bat",
    r"D:\Program Files\hermes\run_hermes.bat",
    r"C:\soft\hermes\run_hermes.bat",
    r"C:\hermes\run_hermes.bat",
    os.path.join(os.environ.get("HERMES_HOME", ""), "run_hermes.bat"),
]
DROP = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY")
KEEP_EXTRA = 'set "TELEGRAM_PROXY=http://127.0.0.1:1089"'

ap = argparse.ArgumentParser()
ap.add_argument("--bat", help="启动脚本路径（不给就自动探测）")
a = ap.parse_args()

BAT = a.bat
if not BAT or not os.path.isfile(BAT):
    for c in BAT_CANDS:
        if c and os.path.isfile(c):
            BAT = c
            break
if not BAT or not os.path.isfile(BAT):
    print("找不到 run_hermes.bat，请用 --bat 指定路径。试过：")
    for c in BAT_CANDS:
        if c:
            print("   ", c)
    sys.exit(1)
print("目标启动脚本:", BAT)

src = open(BAT, encoding="utf-8", errors="ignore").read()
lines = src.splitlines(True)
bak = "%s.bak-%s" % (BAT, time.strftime("%Y%m%d-%H%M%S"))
shutil.copy2(BAT, bak)
print("备份:", bak)

out, dropped, has_tg = [], [], False
for ln in lines:
    up = ln.upper()
    if any(d + "=" in up.replace('"', '').replace('SET ', '') and ln.strip().upper().startswith('SET') and d in up
           for d in DROP) and "NO_PROXY" not in up:
        dropped.append(ln.strip())
        continue
    if "TELEGRAM_PROXY" in up:
        has_tg = True
    out.append(ln)

if not has_tg:
    # 插到最后一条 set 之后
    idx = max((i for i, l in enumerate(out) if l.strip().upper().startswith("SET")), default=0)
    out.insert(idx + 1, KEEP_EXTRA + "\r\n")
    print("已补 TELEGRAM_PROXY")

open(BAT, "w", encoding="utf-8").write("".join(out))
print("删除的全局代理行:")
for d in dropped:
    print("   -", d)
print("\n--- 改后的 run_hermes.bat ---")
for l in open(BAT, encoding="utf-8", errors="ignore").read().splitlines():
    print("   " + l)
