#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Chunked Real-ESRGAN 4x upscale of the 864x480 rv2v clip, downscaled to 1376x768.

Splits the clip into chunks (VHS skip/frame_load_cap) so the 4x batch fits in 16 GB VRAM,
then concatenates the chunks with ffmpeg and remuxes the original audio.
"""
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_firstpass_864x480.mp4"
CHUNK = 65
MODEL = "4x-UltraMix_Balanced.pth"


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_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)
            files = []
            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"):
                            files.append(it)
            for it in files:
                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 / "checks" / f"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 output ({json.dumps(st)[:400]})")
        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):
        skip = i * CHUNK
        tag = f"c{i}"
        out = HERE / "checks" / f"up_{tag}.mp4"
        if only and tag != only:
            continue
        if not out.exists():
            out = run_chunk(skip, CHUNK, tag)
        parts.append(out)
    if only:
        return
    listing = HERE / "checks" / "concat_up.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(HERE / "20261031_KDA神之八秒_粉泳装_4步放大768P.mp4"),
           "-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()
