# -*- coding: utf-8 -*-
"""API prompt'u ComfyUI'a dogrulatir (kuyruga atar, hemen iptal eder)."""
import json, sys, urllib.request, urllib.error, uuid, time

COMFY = "http://127.0.0.1:8188"
API = sys.argv[1] if len(sys.argv) > 1 else "public/comfy/FikoYT-img2-3d.api.json"

prompt = json.load(open(API, "r", encoding="utf-8"))

# LoadImage'i sunucuda gercekten var olan bir input resmiyle degistir
oi = json.loads(urllib.request.urlopen(COMFY + "/api/object_info/LoadImage").read())
secenekler = oi["LoadImage"]["input"]["required"]["image"][0]
print("input resim sayisi:", len(secenekler), "-> secilen:", secenekler[0])
prompt["122"]["inputs"]["image"] = secenekler[0]

body = json.dumps({"prompt": prompt, "client_id": str(uuid.uuid4())}).encode("utf-8")
req = urllib.request.Request(COMFY + "/api/prompt", data=body,
                             headers={"Content-Type": "application/json"})
try:
    r = json.loads(urllib.request.urlopen(req, timeout=60).read())
    print("GECERLI. prompt_id =", r.get("prompt_id"), " node_errors:", r.get("node_errors"))
    time.sleep(1)
    urllib.request.urlopen(urllib.request.Request(COMFY + "/api/interrupt", data=b"{}",
                           headers={"Content-Type": "application/json"}), timeout=30).read()
    urllib.request.urlopen(urllib.request.Request(COMFY + "/api/queue",
                           data=json.dumps({"clear": True}).encode(),
                           headers={"Content-Type": "application/json"}), timeout=30).read()
    print("kuyruk temizlendi.")
except urllib.error.HTTPError as e:
    print("HATA", e.code)
    print(e.read().decode("utf-8", "replace")[:4000])
