#!/usr/bin/env python3
"""Minimal ComfyUI HTTP API client using only the Python standard library.

Queue an API-format workflow, wait for it, and download the output images.

    python3 scripts/comfy_client.py workflows/txt2img_sdxl.api.json \
        --prompt "a lighthouse at dusk, oil painting" --seed 1234 --out outputs/

    # change any input: --set NODE_ID.INPUT=VALUE (VALUE parsed as JSON when possible)
    python3 scripts/comfy_client.py workflows/txt2img_sdxl.api.json --set 5.steps=20 --set 4.width=832

    # upload a local image and use it in a LoadImage node
    python3 scripts/comfy_client.py workflows/img2img_sdxl.api.json --image 4=photo.jpg

Endpoints used (ComfyUI server, default http://127.0.0.1:8188):
    POST /prompt            {"prompt": <graph>, "client_id": <id>} -> {"prompt_id": ...}
    GET  /history/<id>      outputs once finished
    GET  /view?filename=&subfolder=&type=   image bytes
    POST /upload/image      multipart form, field "image"
"""

from __future__ import annotations

import argparse
import json
import mimetypes
import os
import random
import sys
import time
import urllib.parse
import urllib.request
import uuid
from typing import Any, Dict, List, Optional, Tuple

DEFAULT_SERVER = os.environ.get("COMFY_URL", "http://127.0.0.1:8188")


# ---------- graph helpers (pure functions, easy to test) ----------

def parse_value(raw: str) -> Any:
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return raw


def apply_set(graph: dict, assignment: str) -> None:
    """Apply 'NODE.INPUT=VALUE' to the graph in place."""
    target, sep, raw = assignment.partition("=")
    node_id, dot, input_name = target.partition(".")
    if not sep or not dot:
        raise ValueError(f"expected NODE.INPUT=VALUE, got {assignment!r}")
    if node_id not in graph:
        raise KeyError(f"node {node_id} not in workflow")
    graph[node_id]["inputs"][input_name] = parse_value(raw)


def find_nodes(graph: dict, class_type: str) -> List[str]:
    return sorted((nid for nid, n in graph.items() if n.get("class_type") == class_type), key=_id_key)


def _id_key(nid: str):
    return (0, int(nid)) if nid.isdigit() else (1, nid)


def find_by_title(graph: dict, title: str) -> Optional[str]:
    for nid, n in graph.items():
        if n.get("_meta", {}).get("title", "").lower() == title.lower():
            return nid
    return None


def set_prompt(graph: dict, text: str, negative: bool = False) -> str:
    """Set the positive (or negative) prompt. Prefers a node titled 'Positive prompt' /
    'Negative prompt'; otherwise uses the first / second CLIPTextEncode node."""
    title = "Negative prompt" if negative else "Positive prompt"
    nid = find_by_title(graph, title)
    if nid is None:
        encoders = find_nodes(graph, "CLIPTextEncode")
        idx = 1 if negative else 0
        if len(encoders) <= idx:
            raise LookupError(f"no node for {title}")
        nid = encoders[idx]
    graph[nid]["inputs"]["text"] = text
    return nid


def set_seed(graph: dict, seed: int) -> List[str]:
    changed = []
    for nid, n in graph.items():
        inputs = n.get("inputs", {})
        for key in ("seed", "noise_seed"):
            if key in inputs and not isinstance(inputs[key], list):
                inputs[key] = seed
                changed.append(nid)
    return changed


def output_images(history_entry: dict) -> List[Dict[str, str]]:
    images = []
    for node_out in history_entry.get("outputs", {}).values():
        for img in node_out.get("images", []):
            if img.get("type", "output") == "output":
                images.append(img)
    return images


# ---------- HTTP ----------

class ComfyClient:
    def __init__(self, server: str = DEFAULT_SERVER, timeout: float = 30.0):
        self.server = server.rstrip("/")
        self.timeout = timeout
        self.client_id = str(uuid.uuid4())

    def _get(self, path: str) -> bytes:
        with urllib.request.urlopen(self.server + path, timeout=self.timeout) as r:
            return r.read()

    def _post_json(self, path: str, payload: dict) -> dict:
        req = urllib.request.Request(
            self.server + path,
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=self.timeout) as r:
            return json.loads(r.read())

    def queue(self, graph: dict) -> str:
        res = self._post_json("/prompt", {"prompt": graph, "client_id": self.client_id})
        if "prompt_id" not in res:
            raise RuntimeError(f"queue failed: {res}")
        return res["prompt_id"]

    def wait(self, prompt_id: str, poll: float = 1.0, max_wait: float = 3600) -> dict:
        deadline = time.time() + max_wait
        while time.time() < deadline:
            hist = json.loads(self._get(f"/history/{prompt_id}"))
            if prompt_id in hist:
                entry = hist[prompt_id]
                status = entry.get("status", {})
                if status.get("status_str") == "error":
                    raise RuntimeError(f"execution error: {json.dumps(status)[:800]}")
                return entry
            time.sleep(poll)
        raise TimeoutError(f"prompt {prompt_id} not finished after {max_wait}s")

    def download(self, image: Dict[str, str]) -> bytes:
        q = urllib.parse.urlencode(
            {"filename": image["filename"], "subfolder": image.get("subfolder", ""), "type": image.get("type", "output")}
        )
        return self._get(f"/view?{q}")

    def upload_image(self, path: str, overwrite: bool = True) -> str:
        boundary = uuid.uuid4().hex
        name = os.path.basename(path)
        ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
        with open(path, "rb") as f:
            data = f.read()
        body = b"".join([
            f"--{boundary}\r\n".encode(),
            f'Content-Disposition: form-data; name="image"; filename="{name}"\r\n'.encode(),
            f"Content-Type: {ctype}\r\n\r\n".encode(), data, b"\r\n",
            f"--{boundary}\r\n".encode(),
            b'Content-Disposition: form-data; name="overwrite"\r\n\r\n',
            (b"true" if overwrite else b"false"), b"\r\n",
            f"--{boundary}--\r\n".encode(),
        ])
        req = urllib.request.Request(
            self.server + "/upload/image", data=body, method="POST",
            headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
        )
        with urllib.request.urlopen(req, timeout=self.timeout) as r:
            res = json.loads(r.read())
        return res["name"] if not res.get("subfolder") else f"{res['subfolder']}/{res['name']}"


def run(args: argparse.Namespace) -> List[str]:
    with open(args.workflow, encoding="utf-8") as f:
        graph = json.load(f)
    client = ComfyClient(args.server)

    if args.prompt is not None:
        set_prompt(graph, args.prompt)
    if args.negative is not None:
        set_prompt(graph, args.negative, negative=True)
    seed = args.seed if args.seed is not None else random.randint(0, 2**32 - 1)
    set_seed(graph, seed)
    for spec in args.image or []:
        node_id, _, path = spec.partition("=")
        graph[node_id]["inputs"]["image"] = client.upload_image(path)
    for s in args.set or []:
        apply_set(graph, s)

    prompt_id = client.queue(graph)
    print(f"queued {prompt_id} (seed {seed})", file=sys.stderr)
    entry = client.wait(prompt_id)
    os.makedirs(args.out, exist_ok=True)
    saved = []
    for img in output_images(entry):
        dest = os.path.join(args.out, img["filename"])
        with open(dest, "wb") as f:
            f.write(client.download(img))
        saved.append(dest)
        print(dest)
    return saved


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description="Queue a ComfyUI API workflow and save the results.")
    p.add_argument("workflow", help="API-format workflow JSON")
    p.add_argument("--server", default=DEFAULT_SERVER)
    p.add_argument("--prompt", help="positive prompt text")
    p.add_argument("--negative", help="negative prompt text")
    p.add_argument("--seed", type=int, help="seed for every sampler (random if omitted)")
    p.add_argument("--set", action="append", metavar="NODE.INPUT=VALUE", help="override any input")
    p.add_argument("--image", action="append", metavar="NODE=PATH", help="upload PATH and use it in LoadImage NODE")
    p.add_argument("--out", default="outputs", help="folder for downloaded images")
    return p


if __name__ == "__main__":
    run(build_parser().parse_args())
