#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Qwen-Image-2.1 / 2.1-Turbo 出图脚本（走 GPU 机 ComfyUI API）

要点（社区验证的 Turbo 正确跑法）：
  - 官方 Turbo checkpoint 把 8 步采样计划烧进了 model_index.json，
    普通 KSampler 即使写 steps=8 也**复现不出**该计划 → 出图发糊。
  - 必须用 SamplerCustomAdvanced + ManualSigmas 显式给出 sigmas，euler + CFG 1。

用法示例：
  python3 run_qwen21_turbo.py --prompt "一只柯基在雨中弹吉他" --width 1024 --height 1024
  python3 run_qwen21_turbo.py --prompt "..." --width 2048 --height 2048 --seed 42
  python3 run_qwen21_turbo.py --prompt "..." --unet qwen_image_2.1_int8_convrot.safetensors \
      --lora "qwen_image_2.1_turbo_lora_avg_rank_178_bf16.safetensors" --lora-strength 1.0
"""
import argparse
import json
import sys
import threading
import time
import urllib.parse
import urllib.request
import uuid
import subprocess

DEFAULT_SIGMAS = "1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0.0"


def http_json(url, payload=None, timeout=120):
    data = json.dumps(payload).encode() if payload is not None else None
    req = urllib.request.Request(
        url, data=data,
        headers={"Content-Type": "application/json"} if data else {},
    )
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode())


def build_graph_base(a):
    """基线档：官方模板跑法（KSampler + 步数/调度器），用于 A/B 对比"""
    g = {}
    g["1"] = {"class_type": "UNETLoader",
              "inputs": {"unet_name": a.unet, "weight_dtype": "default"}}
    g["2"] = {"class_type": "CLIPLoader",
              "inputs": {"clip_name": a.clip, "type": "qwen_image", "device": "default"}}
    g["3"] = {"class_type": "VAELoader", "inputs": {"vae_name": a.vae}}
    g["4"] = {"class_type": "TextEncodeQwenImage21",
              "inputs": {"clip": ["2", 0], "prompt": a.prompt,
                         "negative_prompt": a.negative,
                         "resolution": a.resolution, "vae": ["3", 0]}}
    g["5"] = {"class_type": "EmptyLatentImage",
              "inputs": {"width": a.width, "height": a.height, "batch_size": 1}}
    g["6"] = {"class_type": "KSampler",
              "inputs": {"model": ["1", 0], "seed": a.seed, "steps": a.steps,
                         "cfg": a.cfg, "sampler_name": a.sampler,
                         "scheduler": a.scheduler, "positive": ["4", 0],
                         "negative": ["4", 1], "latent_image": ["5", 0],
                         "denoise": 1.0}}
    g["11"] = {"class_type": "VAEDecode", "inputs": {"samples": ["6", 0], "vae": ["3", 0]}}
    g["12"] = {"class_type": "SaveImage",
               "inputs": {"images": ["11", 0], "filename_prefix": a.prefix}}
    return g


def build_graph(a):
    if a.mode == "base":
        return build_graph_base(a)
    g = {}
    g["1"] = {"class_type": "UNETLoader",
              "inputs": {"unet_name": a.unet, "weight_dtype": "default"}}
    g["2"] = {"class_type": "CLIPLoader",
              "inputs": {"clip_name": a.clip, "type": "qwen_image", "device": "default"}}
    g["3"] = {"class_type": "VAELoader", "inputs": {"vae_name": a.vae}}

    model_ref = ["1", 0]
    if a.lora:
        g["20"] = {"class_type": "LoraLoaderModelOnly",
                   "inputs": {"model": ["1", 0], "lora_name": a.lora,
                              "strength_model": a.lora_strength}}
        model_ref = ["20", 0]

    g["4"] = {"class_type": "TextEncodeQwenImage21",
              "inputs": {"clip": ["2", 0], "prompt": a.prompt,
                         "negative_prompt": a.negative,
                         "resolution": a.resolution, "vae": ["3", 0]}}
    g["5"] = {"class_type": "EmptyLatentImage",
              "inputs": {"width": a.width, "height": a.height, "batch_size": 1}}
    g["6"] = {"class_type": "KSamplerSelect", "inputs": {"sampler_name": a.sampler}}
    g["7"] = {"class_type": "ManualSigmas", "inputs": {"sigmas": a.sigmas}}
    g["8"] = {"class_type": "CFGGuider",
              "inputs": {"model": model_ref, "positive": ["4", 0],
                         "negative": ["4", 1], "cfg": a.cfg}}
    g["9"] = {"class_type": "RandomNoise", "inputs": {"noise_seed": a.seed}}
    g["10"] = {"class_type": "SamplerCustomAdvanced",
               "inputs": {"noise": ["9", 0], "guider": ["8", 0], "sampler": ["6", 0],
                          "sigmas": ["7", 0], "latent_image": ["5", 0]}}
    g["11"] = {"class_type": "VAEDecode", "inputs": {"samples": ["10", 0], "vae": ["3", 0]}}
    g["12"] = {"class_type": "SaveImage",
               "inputs": {"images": ["11", 0], "filename_prefix": a.prefix}}
    return g


class VramSampler(threading.Thread):
    """采样显存。--vram-ssh 指定远端（本机无 N 卡时通过 ssh 采 GPU 机）"""

    def __init__(self, ssh_host=None, ssh_pass=None):
        super().__init__(daemon=True)
        self.stop_flag = False
        self.peak = 0
        self.samples = []
        self.ssh_host = ssh_host
        self.ssh_pass = ssh_pass

    def _read(self):
        cmd = ["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"]
        if self.ssh_host:
            env = dict(**__import__("os").environ)
            env["SSHPASS"] = self.ssh_pass or ""
            r = subprocess.run(
                ["sshpass", "-e", "ssh", "-o", "StrictHostKeyChecking=no",
                 "-o", "ConnectTimeout=10", self.ssh_host] + cmd,
                capture_output=True, text=True, timeout=20, env=env)
        else:
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
        return r.stdout.strip().splitlines()

    def run(self):
        while not self.stop_flag:
            try:
                out = self._read()
                if out:
                    v = int(out[0])
                    self.samples.append(v)
                    self.peak = max(self.peak, v)
            except Exception:
                pass
            time.sleep(2)


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--host", default="192.168.31.31:8189")
    p.add_argument("--prompt", required=True)
    p.add_argument("--negative", default="")
    p.add_argument("--width", type=int, default=1024)
    p.add_argument("--height", type=int, default=1024)
    p.add_argument("--resolution", type=int, default=1024,
                   help="TextEncodeQwenImage21 的 resolution 参数")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--cfg", type=float, default=1.0)
    p.add_argument("--sampler", default="euler")
    p.add_argument("--sigmas", default=DEFAULT_SIGMAS)
    p.add_argument("--unet", default="qwen_image_2.1_turbo_int8_convrot.safetensors")
    p.add_argument("--clip", default="qwen3vl_8b_w4a8.safetensors")
    p.add_argument("--vae", default="qwen_image_2.1_vae_bf16.safetensors")
    p.add_argument("--lora", default=None)
    p.add_argument("--lora-strength", type=float, default=1.0)
    p.add_argument("--prefix", default="qwen21turbo/t2i")
    p.add_argument("--mode", choices=["turbo", "base"], default="turbo",
                   help="turbo=SamplerCustomAdvanced+ManualSigmas；base=官方模板的 KSampler 跑法")
    p.add_argument("--steps", type=int, default=25, help="仅 base 模式使用")
    p.add_argument("--scheduler", default="simple", help="仅 base 模式使用")
    p.add_argument("--vram-ssh", default=None, help="显存采样用的远端，如 zyw@192.168.31.31")
    p.add_argument("--vram-pass", default=None)
    p.add_argument("--outdir", default=".")
    p.add_argument("--timeout", type=int, default=1800)
    a = p.parse_args()

    base = f"http://{a.host}"
    graph = build_graph(a)
    client_id = str(uuid.uuid4())

    print(f"[cfg] mode={a.mode} unet={a.unet} clip={a.clip} lora={a.lora}")
    print(f"[cfg] {a.width}x{a.height} seed={a.seed} cfg={a.cfg} sampler={a.sampler}")
    if a.mode == "turbo":
        print(f"[cfg] sigmas={a.sigmas}")
    else:
        print(f"[cfg] steps={a.steps} scheduler={a.scheduler}")
    print(f"[cfg] prompt={a.prompt[:80]}", flush=True)

    vs = VramSampler(a.vram_ssh, a.vram_pass)
    vs.start()

    t0 = time.time()
    resp = http_json(f"{base}/prompt", {"prompt": graph, "client_id": client_id})
    if "prompt_id" not in resp:
        print("[FAIL] 提交失败：", json.dumps(resp, ensure_ascii=False)[:2000])
        vs.stop_flag = True
        sys.exit(1)
    pid = resp["prompt_id"]
    print(f"[submit] prompt_id={pid}")

    hist = None
    while time.time() - t0 < a.timeout:
        time.sleep(2)
        try:
            h = http_json(f"{base}/history/{pid}")
        except Exception as e:
            print("  poll err", e)
            continue
        if pid in h:
            hist = h[pid]
            break
        el = time.time() - t0
        if int(el) % 10 < 2:
            print(f"  ... {el:.0f}s  vram_peak={vs.peak}MiB", flush=True)

    vs.stop_flag = True
    elapsed = time.time() - t0

    if hist is None:
        print(f"[FAIL] 超时 {a.timeout}s")
        sys.exit(2)

    status = hist.get("status", {})
    print(f"[status] {status.get('status_str')}  completed={status.get('completed')}")
    if status.get("status_str") == "error":
        for m in status.get("messages", []):
            print("   msg:", json.dumps(m, ensure_ascii=False)[:1500])
        sys.exit(3)

    saved = []
    for node_id, out in hist.get("outputs", {}).items():
        for img in out.get("images", []):
            q = urllib.parse.urlencode({"filename": img["filename"],
                                        "subfolder": img.get("subfolder", ""),
                                        "type": img.get("type", "output")})
            url = f"{base}/view?{q}"
            dst = f"{a.outdir}/{img['filename']}"
            with urllib.request.urlopen(url, timeout=300) as r, open(dst, "wb") as f:
                f.write(r.read())
            saved.append(dst)
            print(f"[saved] {dst}")

    steps_n = len(a.sigmas.split(",")) - 1 if a.mode == "turbo" else a.steps
    print(f"[done] 总耗时 {elapsed:.1f}s | 显存峰值 {vs.peak} MiB | 采样步数 {steps_n}")


if __name__ == "__main__":
    main()
