#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Chunked Real-ESRGAN *anime* 4x upscale of the anime rv2v clip, downscaled to 1376x768."""
import json
import subprocess
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_anime_firstpass.mp4"
CHUNK = 65
MODEL = "RealESRGAN_x4plus_anime_6B.pth"
FIRST = HERE / "20261031_KDA神之八秒_金发制服_动漫版_一采864x480.mp4"


def graph(skip, count, tag):
    return {
        "1": {"class_type": "VHS_LoadVideo", "inputs": {
            "video": SRC, "force_rate": 24.0, "custom_width": 0, "custom_height": 0,
            "frame_load_cap": count, "skip_first_frames": skip, "select_every_nth": 1}},
        "2": {"class_type": "UpscaleModelLoader", "inputs": {"model_name": MODEL}},
        "3": {"class_type": "ImageUpscaleWithModel", "inputs": {"upscale_model": ["2", 0], "image": ["1", 0]}},
        "4": {"class_type": "ImageScale", "inputs": {
            "image": ["3", 0], "upscale_method": "lanczos", "width": 1376, "height": 768, "crop": "disabled"}},
        "5": {"class_type": "VHS_VideoCombine", "inputs": {
            "images": ["4", 0], "frame_rate": 24.0, "loop_count": 0,
            "filename_prefix": f"video/kda_anime_up_{tag}", "format": "video/h264-mp4",
            "pingpong": False, "save_output": True}},
    }


def run_chunk(skip, count, tag):
    r = S.post(f"{BASE}/prompt", json={"prompt": graph(skip, count, tag), "client_id": str(uuid.uuid4())}, timeout=120)
    r.raise_for_status()
    pid = r.json()["prompt_id"]
    t0 = time.time()
    while time.time() - t0 < 2400:
        h = S.get(f"{BASE}/history/{pid}", timeout=60).json()
        if pid in h:
            e = h[pid]
            st = e.get("status", {})
            print(f"[{tag}] status={st.get('status_str')} {int(time.time()-t0)}s", flush=True)
            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", "").lower().endswith(".mp4"):
                            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 / "checks" / f"anime_up_{tag}.mp4"
                            dest.parent.mkdir(exist_ok=True)
                            dest.write_bytes(rr.content)
                            print(f"[{tag}] saved {dest} {len(rr.content)/1e6:.1f} MB", flush=True)
                            return dest
            raise RuntimeError(f"{tag}: no mp4 output")
        time.sleep(10)
    raise TimeoutError(tag)


def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None
    parts = []
    for i in range(4):
        tag = f"c{i}"
        out = HERE / "checks" / f"anime_up_{tag}.mp4"
        if only and tag != only:
            continue
        if not out.exists():
            out = run_chunk(i * CHUNK, CHUNK, tag)
        parts.append(out)
    if only:
        return
    listing = HERE / "checks" / "concat_anime.txt"
    listing.write_text("\n".join(f"file '{p.name}'" for p in parts), encoding="utf-8")
    dest = HERE / "20261031_KDA神之八秒_金发制服_动漫版_RealESRGAN768P.mp4"
    cmd = ["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(listing),
           "-i", str(FIRST), "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest", str(dest)]
    subprocess.run(cmd, check=True, cwd=HERE / "checks")
    print("[done]", dest)


if __name__ == "__main__":
    main()
