#!/usr/bin/env python3
"""Verify official Turbo template + boonude LoRA path via ComfyUI API (flat equivalent graph)."""
import json
import sys
import time
import urllib.request

BASE = "http://127.0.0.1:8189"


def api(path, data=None, timeout=120):
    if data is not None:
        req = urllib.request.Request(
            BASE + path, data=json.dumps(data).encode(),
            headers={"Content-Type": "application/json"})
    else:
        req = urllib.request.Request(BASE + path)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


# Mirrors the official turbo template: UNETLoader -> LoraLoader -> KSampler
# (official params: 4 steps, cfg 1, lcm/sgm_uniform, ConditioningZeroOut negative)
PROMPT_GRAPH = {
    "1": {"class_type": "UNETLoader", "inputs": {"unet_name": "boogu_image_turbo_fp8_scaled.safetensors", "weight_dtype": "default"}},
    "2": {"class_type": "CLIPLoader", "inputs": {"clip_name": "qwen3vl_8b_fp8_scaled.safetensors", "type": "boogu", "device": "default"}},
    "3": {"class_type": "LoraLoader", "inputs": {"model": ["1", 0], "clip": ["2", 0], "lora_name": "boonude.safetensors", "strength_model": 1.0, "strength_clip": 1.0}},
    "4": {"class_type": "VAELoader", "inputs": {"vae_name": "ae.safetensors"}},
    "5": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["3", 1], "text": "A beautiful portrait of a woman in a sunlit garden, soft cinematic lighting, detailed skin texture, professional photography"}},
    "6": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["5", 0]}},
    "7": {"class_type": "EmptyLatentImage", "inputs": {"width": 1024, "height": 1024, "batch_size": 1}},
    "8": {"class_type": "KSampler", "inputs": {"model": ["3", 0], "seed": 896977722960984, "steps": 4, "cfg": 1.0, "sampler_name": "lcm", "scheduler": "sgm_uniform", "denoise": 1.0, "positive": ["5", 0], "negative": ["6", 0], "latent_image": ["7", 0]}},
    "9": {"class_type": "VAEDecode", "inputs": {"samples": ["8", 0], "vae": ["4", 0]}},
    "10": {"class_type": "SaveImage", "inputs": {"images": ["9", 0], "filename_prefix": "Boogu_turbo_lora_verify"}},
}

try:
    resp = api("/prompt", {"prompt": PROMPT_GRAPH, "client_id": "boogu-turbo-lora"})
except Exception as e:
    print("submit error:", e)
    sys.exit(1)
if "prompt_id" not in resp:
    print("validation failed:", json.dumps(resp, ensure_ascii=False)[:1500])
    sys.exit(2)
pid = resp["prompt_id"]
print("submitted", pid, flush=True)
t0 = time.time()
while True:
    time.sleep(15)
    try:
        h = api("/history/" + pid, timeout=30)
    except Exception:
        continue
    if pid in h:
        p = h[pid]
        st = p["status"]["status_str"]
        print(f"status={st} elapsed={time.time()-t0:.0f}s", flush=True)
        for m in p.get("status", {}).get("messages", []):
            if m[0] == "execution_error":
                print("ERROR:", json.dumps(m[1], ensure_ascii=False)[:1500])
        for nid, out in p.get("outputs", {}).items():
            for im in out.get("images", []):
                print("IMAGE:", im["filename"])
        sys.exit(0 if st == "success" else 3)
