# -*- coding: utf-8 -*-
"""固定域名隧道看门狗：每 60 秒确认 usgrad-web 命名隧道在线，掉了自动拉起。
URL: https://usgrad.cn/index_main.html  （Cloudflare 侧 CNAME → 本机 127.0.0.1:8000）
"""
import subprocess, time, pathlib, datetime, urllib.request

BASE = pathlib.Path(r"D:\work buddy\2026-11-05-14-15-52")
EXE = BASE / "tools" / "cloudflared.exe"
CFG = r"C:\Users\buf001\.cloudflared\config.yml"
LOG = BASE / "_tunnel_usgrad.log"
ERR = BASE / "_tunnel_usgrad.err"
LOG2 = BASE / "_tunnel_keep.log"


def note(msg):
    with LOG2.open("a", encoding="utf-8") as f:
        f.write(f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}  {msg}\n")


def tunnel_pids():
    out = subprocess.run(
        ["powershell", "-NoProfile", "-Command",
         "(Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\").CommandLine"],
        capture_output=True, text=True)
    lines = [l for l in out.stdout.splitlines() if "usgrad-web" in l]
    return lines


def local_ok():
    try:
        req = urllib.request.Request("http://127.0.0.1:8000/index_main.html", method="HEAD")
        with urllib.request.urlopen(req, timeout=10) as r:
            return r.getcode() == 200
    except Exception:
        return False


def start():
    p = subprocess.Popen(
        [str(EXE), "tunnel", "--config", CFG, "run", "usgrad-web"],
        cwd=str(BASE),
        stdout=open(LOG, "a", encoding="utf-8"),
        stderr=open(ERR, "a", encoding="utf-8"),
        creationflags=0x00000008 | 0x00000200)
    note(f"已拉起隧道 PID={p.pid}")
    return p


if __name__ == "__main__":
    note("看门狗启动（usgrad-web）")
    while True:
        try:
            if not tunnel_pids():
                note("隧道进程不存在 → 重启")
                start()
                time.sleep(20)
            elif not local_ok():
                note("本机 8000 端口无响应（站点服务可能停了，隧道保持不动）")
        except Exception as e:
            note(f"检查异常：{e}")
        time.sleep(60)
