#!/usr/bin/env python3
"""Render the 4 corrected HAND-ONLY finals from the merged boxes.json.

Runs on the 19103 card via run_py.sh. For each video:
  render_from_boxes.py --video data/uploads/shipinN.mp4
      --boxes data/out/<job>/shipinN_hand_annotated.merged.boxes.json
      --out data/out/<job>/shipinN_hand_final.mp4
then verifies (ffprobe frames/duration + audio present) and uploads to OCS
as <N>_hand_annotated.mp4 (hand-only; the pen pass was stopped because
"marker pen" boxes were mostly white cable connectors, not pens).

Progress: one line per finished video in render_finals.progress.
Usage: nohup ./run_py.sh /tmp/render_finals.py > render_finals_stdout.log 2>&1 &
"""
import json
import os
import subprocess
import sys
import traceback

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
LOG_PATH = os.path.join(PROJECT, "render_finals.log")
PROGRESS_PATH = os.path.join(PROJECT, "render_finals.progress")

JOBS = {
    "shipin1": ("c3de403cfd15", 2682),
    "shipin2": ("4e8924d45d4b", 3262),
    "shipin3": ("fe165602b721", 3187),
    "shipin4": ("e9ff7e814d64", 2389),
}
NAMES = {"shipin1": "视频1", "shipin2": "视频2", "shipin3": "视频3", "shipin4": "视频4"}


def log(msg):
    print(msg, flush=True)
    with open(LOG_PATH, "a", encoding="utf-8") as f:
        f.write(msg + "\n")


def load_progress():
    done = set()
    if os.path.exists(PROGRESS_PATH):
        for line in open(PROGRESS_PATH, encoding="utf-8"):
            line = line.strip()
            if line:
                try:
                    done.add(json.loads(line)["video"])
                except Exception:
                    pass
    return done


def probe(path):
    """Verify with cv2 (frames/fps/resolution) + ffmpeg -i stderr (audio)."""
    import cv2
    cap = cv2.VideoCapture(path)
    nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    cap.release()
    r = subprocess.run(
        [FFMPEG, "-v", "info", "-i", path, "-f", "null", "-"],
        capture_output=True, text=True)
    audio = "Audio:" in (r.stderr or "")
    return {"frames": nframes, "fps": fps, "w": w, "h": h, "audio": audio}


def main():
    done = load_progress()
    log(f"[render] starting, already done: {sorted(done)}")
    for stem in ("shipin1", "shipin2", "shipin3", "shipin4"):
        if stem in done:
            log(f"[{stem}] skipped (already done)")
            continue
        job, expected_frames = JOBS[stem]
        job_dir = os.path.join(OUT_DIR, job)
        src = os.path.join(UPLOADS, f"{stem}.mp4")
        boxes = os.path.join(job_dir, f"{stem}_hand_annotated.merged.boxes.json")
        out = os.path.join(job_dir, f"{stem}_hand_final.mp4")
        ocs_name = f"{NAMES[stem]}_hand_annotated.mp4"
        try:
            log(f"[{stem}] rendering from merged boxes.json")
            r = subprocess.run(
                [sys.executable, os.path.join(PROJECT, "render_from_boxes.py"),
                 "--video", src, "--boxes", boxes, "--out", out],
                capture_output=True, text=True)
            if r.returncode != 0:
                log(f"[{stem}] RENDER FAILED:\n{r.stdout}\n{r.stderr}")
                continue
            info = probe(out)
            nframes = info["frames"]
            dur = nframes / info["fps"] if info["fps"] else 0
            audio = "aac" if info["audio"] else ""
            size = os.path.getsize(out)
            log(f"[{stem}] rendered frames={nframes} (expect {expected_frames}) "
                f"dur={dur:.1f}s {info['w']}x{info['h']} audio={'yes' if info['audio'] else 'MISSING'} size={size}")
            if nframes != expected_frames or not info["audio"]:
                log(f"[{stem}] VERIFY FAILED, not uploading")
                continue
            up = subprocess.run(
                ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                 "--upload-file", out, f"https://ocs.dimond.top/{ocs_name}"],
                capture_output=True, text=True)
            log(f"[{stem}] uploaded {ocs_name}: HTTP {up.stdout.strip()}")
            if up.stdout.strip() != "201":
                log(f"[{stem}] UPLOAD FAILED")
                continue
            with open(PROGRESS_PATH, "a", encoding="utf-8") as f:
                f.write(json.dumps({"video": stem, "ocs": ocs_name,
                                    "frames": nframes, "size": size}) + "\n")
        except Exception:
            log(f"[{stem}] ERROR:\n{traceback.format_exc()}")
            continue
    log("[render] ALL DONE")


if __name__ == "__main__":
    main()
