#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Upscale the 864x480 rv2v first-pass clip to 1376x768 with NVIDIA RTX VSR (ComfyUI API)."""
import json
import sys
import time
import uuid
from pathlib import Path

import requests

BASE = "http://192.168.31.31:8189"
S = requests.Session()
S.trust_env = False
HERE = Path(__file__).resolve().parent
SRC = "kda_firstpass_864x480.mp4"

PROMPT = {
    "1": {"class_type": "VHS_LoadVideo", "inputs": {
        "video": SRC, "force_rate": 24.0, "custom_width": 0, "custom_height": 0,
        "frame_load_cap": 0, "skip_first_frames": 0, "select_every_nth": 1}},
    "2": {"class_type": "DaSiWa_RTX_UpscalerRefiner", "inputs": {
        "images": ["1", 0],
        "denoise": False, "denoise_quality": "Low",
        "deblur": False, "deblur_quality": "Low",
        "upscale": "VSR", "upscale_quality": "Ultra",
        "resize_type": "Manual", "scale": 2.0, "megapixels": 2.0,
        "width": 1376, "height": 768, "divisible_by": "8",
        "ratio_preset": "16:9", "resize_method": "Center Crop (Fill)",
        "device_id": 0, "empty_cache": False, "use_mmap": False, "auto_unload_models": True}},
    "3": {"class_type": "VHS_VideoCombine", "inputs": {
        "images": ["2", 0], "frame_rate": 24.0, "loop_count": 0,
        "filename_prefix": "video/h3_kda_768p", "format": "video/h264-mp4",
        "pingpong": False, "save_output": True, "audio": ["1", 2]}},
}


def main():
    r = S.post(f"{BASE}/prompt", json={"prompt": PROMPT, "client_id": str(uuid.uuid4())}, timeout=120)
    print("[submit]", r.status_code, r.text[:800])
    r.raise_for_status()
    pid = r.json()["prompt_id"]
    t0 = time.time()
    while time.time() - t0 < 3600:
        h = S.get(f"{BASE}/history/{pid}", timeout=60).json()
        if pid in h:
            e = h[pid]
            print("[status]", e.get("status"), f"{int(time.time()-t0)}s")
            outs = []
            for nid, o in (e.get("outputs") or {}).items():
                for key in ("gifs", "videos", "images"):
                    for it in (o.get(key) or []):
                        if isinstance(it, dict) and it.get("filename"):
                            outs.append(it)
            print("[outputs]", outs)
            for it in outs:
                if not it["filename"].lower().endswith(".mp4"):
                    continue
                rr = S.get(f"{BASE}/view", params={"filename": it["filename"], "subfolder": it.get("subfolder", ""), "type": it.get("type", "output")}, timeout=600)
                rr.raise_for_status()
                dest = HERE / "20261031_KDA神之八秒_粉泳装_RTX放大768P.mp4"
                dest.write_bytes(rr.content)
                print("[saved]", dest, f"{len(rr.content)/1e6:.1f} MB")
                return
            return
        print(f"[poll] {int(time.time()-t0)}s", flush=True)
        time.sleep(10)
    raise TimeoutError


if __name__ == "__main__":
    main()
