"""diagnose_render.py — submit Malin's EXACT selfie workflow to ComfyUI and print the REAL error.

Run:  C:\\ComfyUI\\.venv\\Scripts\\python.exe C:\\malin\\diagnose_render.py

It reuses malin.py's own workflow builder, sends it to ComfyUI, then prints ComfyUI's actual
execution error — which node failed and why. No guessing. Paste the whole output back to Calypso.
"""
import sys, os, json, time

sys.path.insert(0, r"C:\malin")
try:
    import requests
except Exception as e:
    print("FATAL: requests not importable:", e); sys.exit(1)

try:
    import malin
    print("OK: imported malin.py")
except Exception as e:
    import traceback
    print("FATAL: could not import malin.py:")
    traceback.print_exc(); sys.exit(1)

# 1) find ComfyUI
base = None
for p in [8000, 8001, 8188, 8189, 8888]:
    try:
        requests.get(f"http://127.0.0.1:{p}/system_stats", timeout=3)
        base = f"http://127.0.0.1:{p}"
        print(f"OK: ComfyUI reachable on {p}")
        break
    except Exception:
        continue
if not base:
    print("FATAL: ComfyUI not reachable on 8000/8001/8188/8189/8888"); sys.exit(1)

# 2) build Malin's exact selfie workflow + submit it
try:
    wf = malin.build_selfie_workflow("full body, head to toe, standing, black lace bra", 12345)
except Exception as e:
    import traceback
    print("FATAL: build_selfie_workflow blew up:")
    traceback.print_exc(); sys.exit(1)

r = requests.post(f"{base}/prompt", json={"prompt": wf}, timeout=30)
print("submit HTTP:", r.status_code)
if r.status_code != 200:
    print("=== ComfyUI REJECTED the workflow (this is the error) ===")
    print(r.text[:4000]); sys.exit(0)

pid = r.json()["prompt_id"]
print("prompt_id:", pid, "- waiting for it to finish/fail...")

for _ in range(150):
    time.sleep(2)
    try:
        h = requests.get(f"{base}/history/{pid}", timeout=30).json()
    except Exception:
        continue
    if pid in h:
        st = h[pid].get("status", {})
        print("\n=== STATUS ===")
        print("status_str:", st.get("status_str"))
        print("completed:", st.get("completed"))
        print("\n=== MESSAGES (the error, if any) ===")
        for m in st.get("messages", []):
            print(json.dumps(m, indent=2)[:6000])
        outs = h[pid].get("outputs", {})
        print("\n=== OUTPUTS ===")
        print("output node keys:", list(outs.keys()))
        for nid, o in outs.items():
            imgs = o.get("images", [])
            print(f"  node {nid}: keys={list(o.keys())} images={len(imgs)}")
        if not outs:
            print("  (no outputs at all - the render errored before producing an image)")
        break
else:
    print("timed out after 5 min - render never finished")
