#!/usr/bin/env python3
"""Hand bbox annotation with MediaPipe HandLandmarker (VIDEO mode).
Input: data/raw/*.mp4  Output: data/out/*_hand_annotated.mp4
Audio: muxed back from source with imageio-ffmpeg binary, video stream copied.
"""
import os, sys, subprocess, glob
import cv2
import mediapipe as mp
from mediapipe.tasks import python as mp_python
from mediapipe.tasks.python import vision

BASE = os.path.dirname(os.path.abspath(__file__))
RAW_DIR = os.path.join(BASE, "data", "raw")
OUT_DIR = os.path.join(BASE, "data", "out")
MODEL = os.path.join(BASE, "models", "hand_landmarker.task")
os.makedirs(OUT_DIR, exist_ok=True)

def ffmpeg_exe():
    try:
        import imageio_ffmpeg
        return imageio_ffmpeg.get_ffmpeg_exe()
    except Exception:
        return "ffmpeg"

def annotate_one(src, dst_video_only, dst_final):
    cap = cv2.VideoCapture(src)
    if not cap.isOpened():
        print(f"FAIL open {src}", flush=True); return False
    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
    print(f"START {os.path.basename(src)} fps={fps} size={w}x{h} frames={n}", flush=True)
    options = vision.HandLandmarkerOptions(
        base_options=mp_python.BaseOptions(model_asset_path=MODEL),
        running_mode=vision.RunningMode.VIDEO,
        num_hands=4,
        min_hand_detection_confidence=0.5,
        min_hand_presence_confidence=0.5,
        min_tracking_confidence=0.5,
    )
    writer = cv2.VideoWriter(dst_video_only, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    frames = 0; hand_frames = 0; total_hands = 0
    with vision.HandLandmarker.create_from_options(options) as landmarker:
        while True:
            ok, frame = cap.read()
            if not ok:
                break
            ts = int(frames * 1000.0 / fps)
            rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            mp_img = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
            try:
                res = landmarker.detect_for_video(mp_img, ts)
            except Exception as e:
                print(f"  detect error frame {frames}: {e}", flush=True); res = None
            if res and res.hand_landmarks:
                hand_frames += 1; total_hands += len(res.hand_landmarks)
                for li, lm in enumerate(res.hand_landmarks):
                    xs = [p.x for p in lm]; ys = [p.y for p in lm]
                    x1 = max(0, int(min(xs) * w) - 20); y1 = max(0, int(min(ys) * h) - 20)
                    x2 = min(w - 1, int(max(xs) * w) + 20); y2 = min(h - 1, int(max(ys) * h) + 20)
                    score = ""
                    try:
                        if res.handedness and li < len(res.handedness) and res.handedness[li]:
                            score = f" {res.handedness[li][0].score:.2f}"
                    except Exception:
                        pass
                    label = f"hand{score}"
                    cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3)
                    (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 2)
                    cv2.rectangle(frame, (x1, max(0, y1 - th - 12)), (x1 + tw + 8, y1), (0, 255, 0), -1)
                    cv2.putText(frame, label, (x1 + 4, y1 - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 2)
            writer.write(frame)
            frames += 1
            if frames % 300 == 0:
                print(f"  {frames}/{n} hand_frames={hand_frames}", flush=True)
    writer.release(); cap.release()
    print(f"VIDEO_ONLY done {frames} frames hand_frames={hand_frames} total_hands={total_hands}", flush=True)
    # mux audio from source
    ff = ffmpeg_exe()
    cmd = [ff, "-y", "-i", dst_video_only, "-i", src, "-map", "0:v:0", "-map", "1:a:0?",
           "-c:v", "copy", "-c:a", "copy", "-shortest", dst_final]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        print(f"  mux failed, using video-only as final: {r.stderr[-500:]}", flush=True)
        os.replace(dst_video_only, dst_final)
    else:
        print(f"DONE {dst_final} size={os.path.getsize(dst_final)}", flush=True)
    return True

def main():
    files = sorted(glob.glob(os.path.join(RAW_DIR, "*.mp4")))
    print(f"found {len(files)} videos", flush=True)
    for src in files:
        name = os.path.splitext(os.path.basename(src))[0]
        tmp = os.path.join(OUT_DIR, name + "_videoonly.mp4")
        final = os.path.join(OUT_DIR, name + "_hand_annotated.mp4")
        if os.path.exists(final):
            print(f"SKIP exists {final}", flush=True); continue
        annotate_one(src, tmp, final)
        if os.path.exists(tmp):
            os.remove(tmp)
    print("ALL DONE", flush=True)

if __name__ == "__main__":
    main()
