#!/usr/bin/env python3
"""RealBasicVSR inference worker for 19106-vsr-upscale.
Usage: vsr_infer.py --input in.mp4 --output out_720p.mp4 --model weights/RealBasicVSR_x4.pth
- Decodes input with OpenCV, runs RealBasicVSR in frame chunks (so a
  5-15 s clip does not blow VRAM on a shared RTX 4080).
- Model is x4: SR frames are written at x4, then ffmpeg downscales them
  in the SAME pipeline with Lanczos to short side 720, keeping aspect.
- Audio is copied unchanged (-c:a copy). Frame count and fps unchanged.
"""
import argparse
import json
import os
import subprocess
import sys
import tempfile
import time

import cv2
import numpy as np
import torch


def probe(path):
    out = subprocess.check_output([
        "ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=width,height,r_frame_rate",
        "-show_entries", "format=duration",
        "-of", "json", path], text=True, timeout=30)
    d = json.loads(out)
    s = d["streams"][0]
    num, den = s["r_frame_rate"].split("/")
    return int(s["width"]), int(s["height"]), float(num) / float(den), float(d["format"]["duration"])


def load_model(weight_path, device):
    # Vendored MMEditing RealBasicVSRNet (see realbasicvsr_arch.py).
    # Checkpoint is MMEditing format: state_dict with 'generator.*' prefix
    # plus a discriminator branch we must drop.
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from realbasicvsr_arch import RealBasicVSRNet
    ckpt = torch.load(weight_path, map_location="cpu", weights_only=False)
    if isinstance(ckpt, dict):
        sd = ckpt.get("state_dict") or ckpt.get("params") or ckpt
    else:
        sd = ckpt
    gen = {}
    for k, v in sd.items():
        if k.startswith("generator."):
            gen[k[len("generator."):]] = v
    if not gen:
        gen = sd
    # Parameters verified against the checkpoint: config name c64b20
    # (64 channels, 20 propagation blocks), propagation block indices
    # 0-19 in the checkpoint, x4 config is_sequential_cleaning=True.
    model = RealBasicVSRNet(mid_channels=64, num_propagation_blocks=20,
                            num_cleaning_blocks=20,
                            is_sequential_cleaning=True)
    missing, unexpected = model.load_state_dict(gen, strict=False)
    print(f"load_state_dict: missing={len(missing)} unexpected={len(unexpected)}", flush=True)
    print(f"missing sample: {missing[:10]}", flush=True)
    print(f"unexpected sample: {unexpected[:10]}", flush=True)
    if len(missing) > 50:
        raise RuntimeError(f"too many missing keys ({len(missing)}); arch mismatch, abort")
    model = model.to(device).eval()
    return model


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", required=True)
    ap.add_argument("--output", required=True)
    ap.add_argument("--model", required=True)
    ap.add_argument("--chunk", type=int, default=25)
    args = ap.parse_args()

    w, h, fps, dur = probe(args.input)
    print(f"input {w}x{h} fps={fps:.3f} duration={dur:.3f}", flush=True)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"device {device}", flush=True)
    model = load_model(args.model, device)

    cap = cv2.VideoCapture(args.input)
    if not cap.isOpened():
        raise RuntimeError("cannot open input video")
    tmpdir = tempfile.mkdtemp(prefix="vsr_sr_")
    sr_dir = os.path.join(tmpdir, "sr")
    os.makedirs(sr_dir, exist_ok=True)
    frame_idx = 0
    chunk = []
    t0 = time.time()
    peak = 0.0

    def flush_chunk(frames):
        nonlocal frame_idx
        if not frames:
            return
        arr = np.stack(frames, axis=0)  # (t, h, w, c) BGR uint8
        arr = np.ascontiguousarray(arr[:, :, :, ::-1])  # to RGB (copy: torch rejects negative strides)
        x = torch.from_numpy(arr).permute(0, 3, 1, 2).float() / 255.0
        x = x.unsqueeze(0).to(device)
        with torch.no_grad():
            out = model(x)
        if isinstance(out, (list, tuple)):
            out = out[0]
        out = out.squeeze(0).clamp(0, 1).cpu()
        for i in range(out.shape[0]):
            img = (out[i].permute(1, 2, 0).numpy() * 255.0).round().astype(np.uint8)
            img = np.ascontiguousarray(img[:, :, ::-1])  # RGB -> BGR for cv2
            cv2.imwrite(os.path.join(sr_dir, f"{frame_idx:06d}.png"), img)
            frame_idx += 1
        del x, out
        if device == "cuda":
            torch.cuda.empty_cache()

    while True:
        ok, frame = cap.read()
        if not ok:
            break
        chunk.append(frame)
        if len(chunk) >= args.chunk:
            flush_chunk(chunk)
            chunk = []
            if device == "cuda":
                peak = max(peak, torch.cuda.max_memory_allocated() / 1e9)
            print(f"  processed {frame_idx} frames, {time.time()-t0:.0f}s", flush=True)
    flush_chunk(chunk)
    cap.release()
    total = frame_idx
    print(f"SR frames written: {total} (x4), elapsed {time.time()-t0:.0f}s, peak VRAM {peak:.1f} GB", flush=True)

    # Encode: SR PNGs -> Lanczos downscale to short side 720 -> remux original audio
    if w >= h:
        scale = "scale=-2:720:flags=lanczos"
    else:
        scale = "scale=720:-2:flags=lanczos"
    cmd = ["ffmpeg", "-y", "-framerate", str(fps), "-i", os.path.join(sr_dir, "%06d.png"),
           "-i", args.input, "-vf", scale, "-map", "0:v", "-map", "1:a",
           "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-preset", "medium",
           "-c:a", "copy", "-shortest", args.output]
    print("encode:", " ".join(cmd), flush=True)
    subprocess.check_call(cmd)
    ow, oh, ofps, odur = probe(args.output)
    print(f"output {ow}x{oh} fps={ofps:.3f} duration={odur:.3f} frames={total}", flush=True)
    if abs(odur - dur) > 0.1:
        raise RuntimeError(f"duration drift: in {dur:.3f} out {odur:.3f}")
    if abs(ofps - fps) > 0.01:
        raise RuntimeError(f"fps drift: in {fps:.3f} out {ofps:.3f}")
    print("VSR_OK", flush=True)


if __name__ == "__main__":
    main()
