#!/usr/bin/env python3
"""Render a final annotated video from a boxes.json + the original video.

Usage (run inside the 19103 card via run_py.sh, which sets LD_LIBRARY_PATH):
  ./run_py.sh render_from_boxes.py --video data/uploads/shipin2.mp4 \
      --boxes data/out/<job>/shipin2_hand_annotated.merged.boxes.json \
      --output data/out/<job>/shipin2_hand_annotated_final.mp4

- Draws each frame's boxes with cv2 (per-box label + color from the
  boxes.json row's "labels"/"colors" fields; falls back to "hand"/green),
  pipes raw frames to the imageio-ffmpeg binary (libx264, crf 18), and
  copies the original audio stream verbatim.
- boxes.json rows: {"frame": int, "boxes": [[x1,y1,x2,y2]...], "conf": [...],
  "labels": [...], "colors": [...]}.
"""
import argparse, json, subprocess, sys

FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
COLOR_MAP = {
    "green": ((0, 255, 0), (0, 0, 0)),
    "yellow": ((0, 255, 255), (0, 0, 0)),
    "blue": ((255, 128, 0), (255, 255, 255)),
    "red": ((0, 0, 255), (255, 255, 255)),
    "purple": ((255, 0, 255), (255, 255, 255)),
}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--video", required=True)
    ap.add_argument("--boxes", required=True)
    ap.add_argument("--output", required=True)
    args = ap.parse_args()

    import cv2
    rows = json.load(open(args.boxes))
    by_frame = {r["frame"]: r for r in rows}
    cap = cv2.VideoCapture(args.video)
    if not cap.isOpened():
        print("cannot open video:", args.video)
        sys.exit(1)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
    print(f"video {w}x{h} fps={fps} frames={total}")

    cmd = [FFMPEG, "-v", "error", "-f", "rawvideo", "-pix_fmt", "bgr24",
           "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",
           "-i", args.video, "-map", "0:v", "-map", "1:a",
           "-c:v", "libx264", "-preset", "fast", "-crf", "18",
           "-c:a", "copy", "-y", args.output]
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
    frame_idx = 0
    drawn = 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        row = by_frame.get(frame_idx)
        if row:
            boxes = row.get("boxes") or []
            confs = row.get("conf") or []
            labels = row.get("labels") or ["hand"] * len(boxes)
            colors = row.get("colors") or ["green"] * len(boxes)
            for box, conf, label, color in zip(boxes, confs, labels, colors):
                x1, y1, x2, y2 = [int(round(v)) for v in box]
                x1, y1 = max(0, x1), max(0, y1)
                x2, y2 = min(w - 1, x2), min(h - 1, y2)
                bg, fg = COLOR_MAP.get(color, COLOR_MAP["green"])
                cv2.rectangle(frame, (x1, y1), (x2, y2), bg, 3)
                text = f"{label} {conf:.2f}"
                (tw, th), base = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 2)
                cv2.rectangle(frame, (x1, y1 - th - 10), (x1 + tw + 8, y1), bg, -1)
                cv2.putText(frame, text, (x1 + 4, y1 - 6),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.9, fg, 2, cv2.LINE_AA)
                drawn += 1
        proc.stdin.write(frame.tobytes())
        frame_idx += 1
        if frame_idx % 500 == 0:
            print(f"  {frame_idx}/{total} frames, {drawn} boxes drawn", flush=True)
    proc.stdin.close()
    proc.wait()
    cap.release()
    print(f"done: {frame_idx} frames, {drawn} boxes drawn -> {args.output}")
    if proc.returncode != 0:
        print("ffmpeg exit code:", proc.returncode)
        sys.exit(1)


if __name__ == "__main__":
    main()
