# -*- coding: utf-8 -*-
"""Uctan uca test: resim -> ComfyUI -> GLB. Frontend ile ayni mantik."""
import json, re, sys, time, urllib.request

COMFY = "http://127.0.0.1:8188"
UZ = ("glb", "gltf", "obj", "stl", "ply", "fbx", "usdz")


def gj(u):
    return json.loads(urllib.request.urlopen(COMFY + u, timeout=60).read())


def pj(u, d):
    r = urllib.request.Request(COMFY + u, data=json.dumps(d).encode(),
                               headers={"Content-Type": "application/json"})
    return json.loads(urllib.request.urlopen(r, timeout=120).read())


def cikti_bul(outputs):
    for nid, o in (outputs or {}).items():
        for k, v in (o or {}).items():
            for x in (v if isinstance(v, list) else [v]):
                if isinstance(x, str):
                    m = re.match(r"^(.*?)(?:\s*\[(\w+)\])?$", x)
                    yol, tip = (m.group(1) or "").strip(), (m.group(2) or "output")
                    if yol.split(".")[-1].lower() in UZ:
                        i = yol.rfind("/")
                        return nid, {"filename": yol[i + 1:] if i >= 0 else yol,
                                     "subfolder": yol[:i] if i >= 0 else "", "type": tip}
                elif isinstance(x, dict) and str(x.get("filename", "")).split(".")[-1].lower() in UZ:
                    return nid, {"filename": x["filename"], "subfolder": x.get("subfolder", ""),
                                 "type": x.get("type", "output")}
    return None, None


def node_bul(p, sinif, baslik=None):
    for i, n in p.items():
        if n.get("class_type") == sinif and (baslik is None or n.get("_meta", {}).get("title") == baslik):
            return i
    return None


def main():
    p = json.load(open("public/comfy/FikoYT-img2-3d.api.json", encoding="utf-8"))

    resim = sys.argv[1] if len(sys.argv) > 1 else \
        gj("/api/object_info/LoadImage")["LoadImage"]["input"]["required"]["image"][0][0]
    p[node_bul(p, "LoadImage")]["inputs"]["image"] = resim

    sw = node_bul(p, "ComfySwitchNode", "Switch: Remove background")
    if sw:
        p[sw]["inputs"]["switch"] = True
    tex = node_bul(p, "PrimitiveInt", "Texture Resolution")
    if tex:
        p[tex]["inputs"]["value"] = 1024        # test icin hizli
    print("resim:", resim, "| tex node:", tex, "| switch node:", sw)

    r = pj("/api/prompt", {"prompt": p, "client_id": "fikoyt-test"})
    pid = r["prompt_id"]
    print("prompt_id:", pid, "node_errors:", r.get("node_errors"))

    t0 = time.time()
    while time.time() - t0 < 1500:
        time.sleep(5)
        g = gj("/api/history/" + pid).get(pid)
        if not g:
            continue
        st = g.get("status", {})
        if st.get("completed") or g.get("outputs"):
            print("BITTI  sure=%.0fs  durum=%s" % (time.time() - t0, st.get("status_str")))
            nid, d = cikti_bul(g.get("outputs"))
            print("3D cikti node:", nid, "->", d)
            if d:
                q = "filename=%s&subfolder=%s&type=%s" % (d["filename"], d["subfolder"], d["type"])
                b = urllib.request.urlopen(COMFY + "/api/view?" + q, timeout=300).read()
                open("D:/__sistem__/Masaustu/fikoyt-ai3d-test." + d["filename"].split(".")[-1], "wb").write(b)
                print("indirildi, byte:", len(b))
            return
        if st.get("status_str") == "error":
            print("HATA:", json.dumps(st, ensure_ascii=False)[:2000])
            return
        print("  ... %.0fs" % (time.time() - t0))
    print("zaman asimi")


main()
