#!/opt/homebrew/bin/python3.11
"""
Export Person Thumbnails
職責：從聚類後的數據中提取每個 Person 的臉部截圖，用於確認身份。
"""

import cv2
import json
import os

# 設定
OUTPUT_DIR = "output/quick_preview"
VIDEO_PATH = os.path.join(OUTPUT_DIR, "preview.mp4")
JSON_PATH = os.path.join(OUTPUT_DIR, "preview.face_clustered.json")


def main():
    if not os.path.exists(VIDEO_PATH):
        print("❌ Video not found.")
        return
    if not os.path.exists(JSON_PATH):
        print("❌ Clustered JSON not found.")
        return

    print(f"🔍 Extracting person thumbnails from {JSON_PATH}...")

    with open(JSON_PATH) as f:
        data = json.load(f)

    cap = cv2.VideoCapture(VIDEO_PATH)
    saved_persons = set()

    for frame_obj in data.get("frames", []):
        ts = frame_obj.get("timestamp")
        faces = frame_obj.get("faces", [])

        for face in faces:
            pid = face.get("person_id")

            # 如果這個 Person ID 還沒被存過
            if pid and pid not in saved_persons:
                # 定位到該時間點
                cap.set(cv2.CAP_PROP_POS_MSEC, ts * 1000)
                ret, frame = cap.read()

                if ret:
                    x, y, w, h = face["x"], face["y"], face["width"], face["height"]

                    # 稍微擴大裁剪範圍以包含完整臉部特徵
                    margin = 5
                    crop = frame[
                        max(0, y - margin) : y + h + margin,
                        max(0, x - margin) : x + w + margin,
                    ]

                    out_path = os.path.join(OUTPUT_DIR, f"{pid}.jpg")
                    cv2.imwrite(out_path, crop)
                    print(f"✅ Saved {pid} to {out_path}")
                    saved_persons.add(pid)

    cap.release()
    print(f"\n🎉 Finished! Saved {len(saved_persons)} unique person thumbnails.")


if __name__ == "__main__":
    main()
