#!/usr/bin/env python3
"""
old_machine_check.py — 旧机（ubu015）跨机对照（2026-12-04）
=====================================================
🔴 为什么要独立成文件：
   原本这段逻辑内嵌在 heartbeat_quickcheck.sh 的 heredoc 里 → bash 会提前展开
   `$`、反引号、引号 → 脚本报 `old_log_lines=0`（假数据），而单独跑明明有 214 行。
   **嵌套 heredoc 里的 python 代码不可靠** → 一律抽成独立 .py 文件调用。

🔴 历史坑（同一个坑踩了两次）：
   `logs.tail` 单次上限约 200~215 行（truncated:true）。
   - 传 `{"limit":1200}` → **返回 0 行**（不是截断，是空）→ 曾误判「旧机不再受害」
   - 不传参数 → 正常返回 ~210 行 ✅
   → 判据：**取不到日志 ≠ 现象消失**。必须先看 meta.truncated / cursor / size。

用法：python3 scripts/old_machine_check.py [--json]
输出：一行摘要（旧机日志行数 / 错误命中数 / 最后错误时间 / heartbeat 状态）
"""
import json
import sys
import os
import re
import subprocess
import sys

OLD_URL = "ws://127.0.0.1:59999"


def _find_token(o):
    """在 secrets.json 任意层级找 gateway auth token（长度 >20 的字符串）"""
    if isinstance(o, dict):
        for k, v in o.items():
            if isinstance(v, str) and k.lower().endswith("token") and len(v) > 20:
                return v
            r = _find_token(v)
            if r:
                return r
    elif isinstance(o, list):
        for v in o:
            r = _find_token(v)
            if r:
                return r
    return None


def gcall(method, params=None, timeout=45):
    tok = _find_token(json.load(open(os.path.expanduser("~/.openclaw/secrets.json"))))
    if not tok:
        return {}
    # 🔴 2026-12-04 19:30 修：CLI 默认内部超时只有 10000ms，
    #   旧机走 Tailscale DERP relay（433ms RTT）+ 事件循环忙 → RPC 常在 10s 处被客户端掐断。
    #   实测：logs.tail 不带 limit → gateway timeout；limit=200 → 11.4s 成功；limit=400 → 超时。
    cmd = ["timeout", str(timeout), "openclaw", "gateway", "call",
           "--url", OLD_URL, "--token", tok, method,
           "--timeout", str(int(timeout * 1000))]
    if params:
        cmd += ["--params", params]
    cmd += ["--json"]
    p = subprocess.run(cmd, capture_output=True, text=True)
    try:
        return json.loads(p.stdout)
    except Exception:
        return {}


def main():
    d = gcall("logs.tail", json.dumps({"limit": 200}))
    lines = d.get("lines") or []
    # 🔴 反假绿灯：探针失败**必须显式报失败**，绝不能把「拿不到数据」当成「旧机一切正常」
    if d.get("ok") is False or not lines:
        err = d.get("error") or {}
        print(f"old_machine: PROBE_FAILED lines={len(lines)} "
              f"err={err.get('type', 'unknown')}/{err.get('kind', '')} "
              f"msg={str(err.get('message', ''))[:90]}")
        sys.exit(2)
    meta = {k: v for k, v in d.items() if k != "lines"}

    hits = 0
    last = ""
    last_window = ""
    for l in lines:
        try:
            j = json.loads(l)
        except Exception:
            continue
        t = j.get("time", "")[11:19]
        m = str(j.get("message", ""))
        if t:
            last_window = t
        if re.search(r"rate limit|FailoverError|AbortError|lane task error", m):
            hits += 1
            last = t

    st = gcall("status")
    hb = []
    for a in ((st.get("heartbeat") or {}).get("agents") or []):
        if a.get("enabled"):
            hb.append(f"{a.get('agentId')}@{a.get('every')}")

    out = {
        "old_log_lines": len(lines),
        "truncated": meta.get("truncated"),
        "window_end": last_window,
        "err_hits": hits,
        "last_err": last or "none",
        "heartbeat": ",".join(hb) or "none",
    }
    if "--json" in sys.argv:
        print(json.dumps(out, ensure_ascii=False))
    else:
        print("old_machine: " + " ".join(f"{k}={v}" for k, v in out.items()))
    return 0


if __name__ == "__main__":
    sys.exit(main())
