#!/usr/bin/env python3
"""H3-Image 出图：mode=edit（参考图身份锚定）或 t2i（纯文生图）。

用法: python3 h3img_run_edit.py --mode edit --ref IMG --prompt-file P.txt --size 1440x2560 --seeds 111 222
"""
import argparse, json, mimetypes, os, random, time, urllib.parse, urllib.request, uuid

GPU = "http://192.168.31.31:8189"
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))


def post_json(path, payload):
    req = urllib.request.Request(GPU + path, data=json.dumps(payload).encode(),
                                 headers={"Content-Type": "application/json"})
    with OPENER.open(req, timeout=120) as r:
        return json.loads(r.read())


def get_json(path):
    with OPENER.open(GPU + path, timeout=120) as r:
        return json.loads(r.read())


def upload_image(path):
    boundary = "----dsh" + uuid.uuid4().hex
    with open(path, "rb") as f:
        data = f.read()
    ctype = mimetypes.guess_type(path)[0] or "image/png"
    name = os.path.basename(path)
    body = b""
    body += f"--{boundary}\r\n".encode()
    body += f'Content-Disposition: form-data; name="image"; filename="{name}"\r\n'.encode()
    body += f"Content-Type: {ctype}\r\n\r\n".encode()
    body += data + b"\r\n"
    body += f"--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n".encode()
    body += f"--{boundary}--\r\n".encode()
    req = urllib.request.Request(GPU + "/upload/image", data=body,
                                 headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
    with OPENER.open(req, timeout=300) as r:
        return json.loads(r.read())


def build(seed, prompt, w, h, ref_name=None, prefix="h3img/sh-edit"):
    g = {
        "1": {"class_type": "UNETLoader", "inputs": {
            "unet_name": "minimax_h3_image_pruned_w4a8.safetensors", "weight_dtype": "default"}},
        "2": {"class_type": "CLIPLoader", "inputs": {
            "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
            "type": "minimax", "device": "default"}},
        "3": {"class_type": "VAELoader", "inputs": {"vae_name": "minimax_h3_image_vae_fp16.safetensors"}},
        "4": {"class_type": "MiniMaxH3ImageConditioning", "inputs": {
            "clip": ["2", 0], "vae": ["3", 0], "prompt": prompt, "width": w, "height": h}},
        "5": {"class_type": "ConditioningZeroOut", "inputs": {"conditioning": ["4", 0]}},
        "6": {"class_type": "KSampler", "inputs": {
            "model": ["1", 0], "positive": ["4", 0], "negative": ["5", 0],
            "latent_image": ["4", 1], "seed": seed, "steps": 6, "cfg": 1.0,
            "sampler_name": "euler", "scheduler": "simple", "denoise": 1.0}},
        "7": {"class_type": "VAEDecode", "inputs": {"samples": ["6", 0], "vae": ["3", 0]}},
        "8": {"class_type": "SaveImage", "inputs": {"images": ["7", 0], "filename_prefix": prefix}},
    }
    if ref_name:
        g["10"] = {"class_type": "LoadImage", "inputs": {"image": ref_name}}
        g["4"]["inputs"]["images"] = {"image_1": ["10", 0]}
    return g


def fetch(img, outdir):
    q = urllib.parse.urlencode({"filename": img["filename"], "subfolder": img.get("subfolder", ""),
                                "type": img.get("type", "output")})
    with OPENER.open(f"{GPU}/view?{q}", timeout=300) as r:
        data = r.read()
    name = f"{img['filename']}"
    p = os.path.join(outdir, name)
    with open(p, "wb") as f:
        f.write(data)
    return p


def run(seed, prompt, w, h, ref_name, prefix, outdir):
    pid = post_json("/prompt", {"prompt": build(seed, prompt, w, h, ref_name, prefix),
                                "client_id": "dsh-h3img"})["prompt_id"]
    print(f"[submit] seed={seed} pid={pid}", flush=True)
    t0 = time.time()
    while True:
        time.sleep(4)
        try:
            hist = get_json(f"/history/{pid}")
        except Exception as e:
            print("  poll err", e, flush=True)
            continue
        if pid not in hist:
            if time.time() - t0 > 2400:
                raise TimeoutError(pid)
            continue
        entry = hist[pid]
        st = entry.get("status", {})
        if st.get("status_str") == "error":
            raise RuntimeError(json.dumps([m for m in st.get("messages", []) if m[0] == "execution_error"], ensure_ascii=False)[:1500])
        if entry.get("completed", st.get("completed", False)):
            imgs = [i for o in entry.get("outputs", {}).values() for i in o.get("images", [])]
            paths = [fetch(i, outdir) for i in imgs]
            print(f"[done] {time.time()-t0:.0f}s {paths}", flush=True)
            return {"seed": seed, "secs": round(time.time() - t0, 1), "files": paths, "prompt_id": pid}


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--mode", choices=["edit", "t2i"], default="t2i")
    ap.add_argument("--ref")
    ap.add_argument("--prompt-file", required=True)
    ap.add_argument("--size", default="1440x2560")
    ap.add_argument("--seeds", nargs="*", type=int, default=[])
    ap.add_argument("--num", type=int, default=2)
    ap.add_argument("--outdir", default="/home/zyw/temp/h3img_out")
    ap.add_argument("--prefix", default="h3img/sh-edit")
    a = ap.parse_args()

    os.makedirs(a.outdir, exist_ok=True)
    prompt = open(a.prompt_file, encoding="utf-8").read().strip()
    w, h = [int(x) for x in a.size.split("x")]
    seeds = a.seeds or [random.randint(10**8, 10**9 - 1) for _ in range(a.num)]
    ref = None
    if a.mode == "edit":
        up = upload_image(a.ref)
        ref = up.get("name")
        if up.get("subfolder"):
            ref = f"{up['subfolder']}/{ref}"
        print("[upload]", up, flush=True)

    res = [run(s, prompt, w, h, ref, a.prefix, a.outdir) for s in seeds]
    meta = {"mode": a.mode, "ref": ref, "size": [w, h], "prompt": prompt,
            "results": [{k: v for k, v in r.items() if k != "prompt"} for r in res]}
    with open(os.path.join(a.outdir, "run_meta.json"), "w", encoding="utf-8") as f:
        json.dump(meta, f, ensure_ascii=False, indent=2)
    print(json.dumps(meta["results"], ensure_ascii=False, indent=2))
