#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""comfy_client.py —— 驱动本机 GPU 机上那台 ComfyUI 的最小可复用客户端。

来源：grok CLI 会话 01a0d2df（2026-09-24 → 10-11）实际用法的归纳，见
      dl-hub/06-ComfyUI-H3运维记录/2026-10-11-grok调用ComfyUI机制核查.md 第 9 节。

设计取舍（照抄 grok 踩过的坑）：
  * 只用**标准库**（urllib + subprocess），所以 /usr/bin/python3 直接能跑，
    不需要 vlm-env 那套 requests/numpy。
  * 一律**绕开本机代理**：urllib 用 ProxyHandler({})，curl 用 --noproxy '*'，
    curl/ssh 绑 --interface / -o BindInterface 到局域网网卡（默认 enp3s0f1）。
  * 完成判定默认走 **SSH 读日志增量 + 输出 glob**（比 /history 稳：崩机时日志仍有 Xid 指纹）。
  * 停 ComfyUI 用遍历 /proc 找 pid，**不用 pkill -f**（那条命令会匹配到 ssh 自身 -> 自杀）。

用法：
    python3 comfy_client.py selftest          # 只探活，不提交任何任务
    python3 comfy_client.py queue             # 打印 running/pending
    python3 comfy_client.py restart           # 停+起 ComfyUI 并等 /system_stats 200

    在别的脚本里：
        from comfy_client import Comfy
        c = Comfy()
        c.upload("ref.mp4", "m107_ref.mp4", mime="video/mp4")
        c.wait_idle()
        off = c.log_offset()
        pid = c.submit(api, prefix_hint="video/h3_job")
        remote = c.wait_done("video/h3_job", off, timeout_min=90)
        c.scp_get(remote, "./out.mp4")
"""
from __future__ import annotations

import json
import os
import subprocess
import sys
import time
import urllib.parse
import urllib.request

# ---------------------------------------------------------------- 环境常量
COMFY = os.environ.get("COMFY_URL", "http://192.168.31.31:8189")
GPU = os.environ.get("COMFY_SSH", "zyw@192.168.31.31")
IFACE = os.environ.get("COMFY_IFACE", "enp3s0f1")          # 面向局域网的那块网卡
KEY = os.environ.get("COMFY_SSH_KEY", os.path.expanduser("~/.ssh/id_ed25519_gallery"))
REMOTE_LOG = os.environ.get("COMFY_LOG", "/home/zyw/comfyui_8189.log")
REMOTE_OUT = "/home/zyw/ComfyUI/output"

SSH = ["ssh", "-i", KEY, "-o", f"BindInterface={IFACE}", "-o", "ConnectTimeout=15",
       "-o", "StrictHostKeyChecking=accept-new", GPU]
SCP = ["scp", "-i", KEY, "-o", f"BindInterface={IFACE}"]

# 判定"这次任务挂了"的日志指纹（grok 用的同一套）
FAIL_FLAGS = ("OutOfMemoryError", "CUDA out of memory", "execution_error",
              "NVRM: Xid", "fallen off the bus", "unspecified launch failure",
              "AcceleratorError")

_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))   # 关键：不吃 ALL_PROXY


class ComfyError(RuntimeError):
    pass


class Comfy:
    # ------------------------------------------------------------ HTTP
    def _open(self, req, timeout=60):
        try:
            with _OPENER.open(req, timeout=timeout) as r:
                return json.load(r)
        except urllib.error.HTTPError as exc:                      # noqa: F821
            raise ComfyError(f"HTTP {exc.code}: {exc.read().decode('utf-8', 'replace')[:1500]}") from exc

    def stats(self) -> dict:
        with _OPENER.open(f"{COMFY}/system_stats", timeout=15) as r:
            return json.load(r)

    def queue(self) -> tuple[int, int]:
        """→ (running, pending)"""
        d = self._open(urllib.request.Request(f"{COMFY}/queue"), timeout=20)
        return len(d.get("queue_running") or []), len(d.get("queue_pending") or [])

    def object_info(self, class_type: str | None = None) -> dict:
        url = f"{COMFY}/object_info" + (f"/{class_type}" if class_type else "")
        return self._open(urllib.request.Request(url), timeout=30)

    def history(self, prompt_id: str) -> dict:
        return self._open(urllib.request.Request(f"{COMFY}/history/{prompt_id}"), timeout=60)

    # ------------------------------------------------------------ 上传 / 提交 / 取回
    def upload(self, local: str, remote_name: str | None = None, mime: str = "image/jpeg") -> str:
        """图片和视频都走 /upload/image（ComfyUI 不校验扩展名）。curl 做 multipart。"""
        if not os.path.isfile(local):
            raise ComfyError(f"本地文件不存在: {local}")
        remote_name = remote_name or os.path.basename(local)
        cmd = ["curl", "-sS", "--noproxy", "*", "--interface", IFACE, "--max-time", "900",
               "-F", f"image=@{local};type={mime}",
               "-F", "type=input", "-F", "overwrite=true",
               f"{COMFY}/upload/image"]
        r = subprocess.run(cmd, capture_output=True, text=True)
        if r.returncode != 0:
            raise ComfyError(f"上传失败: {r.stderr[-500:]}")
        return remote_name

    def submit(self, api: dict, client_id: str | None = None) -> str:
        body = json.dumps({"prompt": api,
                           "client_id": client_id or f"dsh-{int(time.time())}"}).encode()
        d = self._open(urllib.request.Request(
            f"{COMFY}/prompt", data=body, headers={"Content-Type": "application/json"}), timeout=60)
        if "prompt_id" not in d:
            raise ComfyError(f"提交被拒: {json.dumps(d, ensure_ascii=False)[:1500]}")
        return d["prompt_id"]

    def view_get(self, filename: str, dest: str, subfolder: str = "",
                 type_: str = "output", timeout: int = 1800) -> str:
        qs = urllib.parse.urlencode({"filename": filename, "subfolder": subfolder, "type": type_})
        with _OPENER.open(f"{COMFY}/view?{qs}", timeout=timeout) as r, open(dest, "wb") as fh:
            fh.write(r.read())
        return dest

    def save_outputs(self, rec: dict, outdir: str) -> list[str]:
        """从 /history 记录里把 images/videos/gifs 全部落到 outdir。"""
        saved = []
        for _nid, out in (rec.get("outputs") or {}).items():
            for key in ("images", "videos", "gifs"):
                for item in out.get(key) or []:
                    dst = os.path.join(outdir, item["filename"])
                    self.view_get(item["filename"], dst, item.get("subfolder", ""),
                                  item.get("type", "output"))
                    saved.append(dst)
        return saved

    # ------------------------------------------------------------ SSH
    @staticmethod
    def ssh(*args: str, timeout: int = 60) -> str:
        r = subprocess.run(SSH + list(args), capture_output=True, text=True, timeout=timeout)
        if r.returncode != 0:
            raise ComfyError(f"ssh 失败({r.returncode}): {(r.stderr or r.stdout)[-500:]}")
        return r.stdout

    def scp_get(self, remote: str, dest: str, timeout: int = 1800) -> str:
        os.makedirs(os.path.dirname(os.path.abspath(dest)) or ".", exist_ok=True)
        subprocess.run(SCP + [f"{GPU}:{remote}", dest], check=True, timeout=timeout)
        return dest

    def log_offset(self) -> int:
        return int(self.ssh(f"stat -c %s {REMOTE_LOG}").strip())

    # ------------------------------------------------------------ 等待 / 判定
    def wait_idle(self, tries: int = 1, gap: int = 10) -> None:
        """不插队：队列非空就报错（grok 的 queue_idle()）。"""
        for _ in range(tries):
            running, pending = self.queue()
            if not running and not pending:
                return
            time.sleep(gap)
        raise ComfyError(f"队列不空 running={running} pending={pending}，拒绝插队")

    def wait_up(self, timeout_s: int = 200) -> None:
        t0 = time.time()
        while time.time() - t0 < timeout_s:
            try:
                self.stats()
                return
            except Exception:                                   # noqa: BLE001
                time.sleep(5)
        raise ComfyError(f"ComfyUI 没有在 {timeout_s}s 内起来")

    def _snapshot(self, glob_pat: str, offset: int) -> dict:
        """读日志 offset 之后的增量 + output glob，返回结构化状态。"""
        probe = f"""python3 - <<'PY'
import glob, os
off = {offset}
text = ''
try:
    with open({REMOTE_LOG!r}, 'rb') as f:
        f.seek(off); text = f.read().decode('utf-8', 'replace')
except FileNotFoundError:
    pass
flags = [k for k in {FAIL_FLAGS!r} if k in text]
files = sorted(glob.glob({glob_pat!r}), key=os.path.getmtime)
newest = files[-1] if files else ''
print('FLAGS', ','.join(flags))
print('EXECUTED', int('Prompt executed in' in text))
print('FILE', newest)
print('SIZE', os.path.getsize(newest) if newest else 0)
PY"""
        out = self.ssh(probe, timeout=40)
        st = {"flags": "", "executed": "0", "file": "", "size": "0", "raw": out}
        for line in out.splitlines():
            for key, name in (("FLAGS ", "flags"), ("EXECUTED ", "executed"),
                              ("FILE ", "file"), ("SIZE ", "size")):
                if line.startswith(key):
                    st[name] = line[len(key):].strip()
        return st

    def wait_done(self, prefix: str, offset: int, timeout_min: int = 90,
                  poll: int = 20, min_size: int = 100_000) -> str:
        """等 output/<prefix>*.mp4 出现且日志说 Prompt executed。返回远端路径。

        offset = 提交前 log_offset() 的值 —— 只看新增日志，避免把上一次任务的报错误判成这一次。
        """
        pattern = f"{REMOTE_OUT}/{prefix}*.mp4"
        deadline = time.time() + timeout_min * 60
        while time.time() < deadline:
            try:
                st = self._snapshot(pattern, offset)
            except ComfyError as exc:                            # SSH 暂时连不上就继续等
                if any(s in str(exc) for s in ("timed out", "Connection refused",
                                               "Connection reset", "No route to host")):
                    print(f"  [wait] ssh 暂不可达，继续等: {str(exc)[-160:]}", flush=True)
                    time.sleep(poll)
                    continue
                raise
            if st["flags"]:
                raise ComfyError(f"任务失败 {prefix}: {st['flags']}\n{st['raw']}")
            if st["executed"] == "1" and st["file"] and int(st["size"] or 0) > min_size:
                return st["file"]
            time.sleep(poll)
        raise TimeoutError(f"等 {prefix} 超时（{timeout_min} 分钟）")

    def wait_history(self, prompt_id: str, poll: int = 20, timeout_min: int = 90) -> dict:
        """另一条路：轮询 /history/{pid}（老脚本用法；崩机时不可靠，优先用 wait_done）。"""
        deadline = time.time() + timeout_min * 60
        while time.time() < deadline:
            try:
                hist = self.history(prompt_id)
            except Exception:                                    # noqa: BLE001
                hist = {}
            rec = hist.get(prompt_id)
            if rec:
                s = rec.get("status") or {}
                print(f"  [hist] status={s.get('status_str')} completed={s.get('completed')}", flush=True)
                if s.get("completed") or s.get("status_str") in ("error", "failed"):
                    return rec
            time.sleep(poll)
        raise TimeoutError(f"等 {prompt_id} 超时")

    # ------------------------------------------------------------ 重启（丢 CUDA 上下文）
    @staticmethod
    def _ssh_stdin(script: str, timeout: int = 60) -> str:
        r = subprocess.run(SSH + ["bash -s"], input=script, capture_output=True,
                           text=True, timeout=timeout)
        if r.returncode != 0:
            raise ComfyError(f"ssh 失败({r.returncode}): {(r.stderr or r.stdout)[-500:]}")
        return r.stdout

    STOP_SCRIPT = r"""
pid=""
for d in /proc/[0-9]*; do
  cmd=$(tr "\0" " " < "$d/cmdline" 2>/dev/null || true)
  case "$cmd" in
    *venv/bin/python*main.py*--port\ 8189*) pid=${d#/proc/} ;;
  esac
done
if [ -z "$pid" ]; then echo "comfy already down"; exit 0; fi
echo "stop comfy pid $pid"
kill "$pid" || true
for _ in $(seq 1 15); do kill -0 "$pid" 2>/dev/null || exit 0; sleep 1; done
kill -9 "$pid" || true; sleep 1
kill -0 "$pid" 2>/dev/null && exit 1 || exit 0
"""

    def stop(self) -> None:
        print(self._ssh_stdin(self.STOP_SCRIPT, timeout=60).strip(), flush=True)

    def start(self) -> None:
        self.ssh("bash ~/restart_comfy.sh", timeout=60)

    def restart(self) -> None:
        self.stop()
        self.start()
        self.wait_up()


# ---------------------------------------------------------------- selftest
def _selftest() -> int:
    c = Comfy()
    ok = True
    print(f"COMFY   = {COMFY}\nIFACE   = {IFACE}\nSSH     = {GPU}\nKEY     = {KEY}\nLOG     = {REMOTE_LOG}")
    try:
        st = c.stats()
        sysinfo = st.get("system", {})
        print(f"[1] /system_stats  OK  comfyui_version={sysinfo.get('comfyui_version')} "
              f"ram_free={sysinfo.get('ram_free')}")
    except Exception as exc:                                     # noqa: BLE001
        ok = False; print(f"[1] /system_stats  FAIL {exc}")
    try:
        running, pending = c.queue()
        print(f"[2] /queue          OK  running={running} pending={pending}")
    except Exception as exc:                                     # noqa: BLE001
        ok = False; print(f"[2] /queue          FAIL {exc}")
    try:
        info = c.object_info("UNETLoader")
        print(f"[3] /object_info    OK  UNETLoader.input={list((info['UNETLoader']['input'].get('required') or {}))}")
    except Exception as exc:                                     # noqa: BLE001
        ok = False; print(f"[3] /object_info    FAIL {exc}")
    try:
        off = c.log_offset()
        snap = c._snapshot(f"{REMOTE_OUT}/__selftest__*.mp4", off)
        print(f"[4] ssh+日志增量    OK  log_offset={off} executed={snap['executed']} flags='{snap['flags']}'")
    except Exception as exc:                                     # noqa: BLE001
        ok = False; print(f"[4] ssh+日志增量    FAIL {exc}")
    print("SELFTEST", "PASS" if ok else "FAIL", "（未提交任何任务）")
    return 0 if ok else 1


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "selftest"
    c = Comfy()
    if cmd == "selftest":
        sys.exit(_selftest())
    if cmd == "queue":
        running, pending = c.queue()
        print(f"running={running} pending={pending}"); sys.exit(0)
    if cmd == "restart":
        c.restart(); print("comfy up"); sys.exit(0)
    if cmd == "stop":
        c.stop(); sys.exit(0)
    raise SystemExit(f"未知子命令 {cmd}；可用: selftest / queue / restart / stop")
