#!/usr/bin/env python3
"""
Build index classifying all Burup archive items into:
- motion: photos that have an associated motion microvideo (10,884)
- dedicated_video: standalone recorded camera videos (140)
- still: still photographs without motion (11,372)
"""

import os
import glob
import json
from collections import Counter

PHOTOS_DIR = "/home/flancian/Burup/photos"
VIDEOS_DIR = "/home/flancian/Burup/videos"
PHOTOS_MANIFEST = "/home/flancian/Burup/burup_photos_manifest.json"
DEDICATED_MANIFEST = "/home/flancian/Burup/burup_videos_manifest.json"
MOTION_MANIFEST = "/home/flancian/Burup/burup_motion_manifest.json"
OUTPUT_INDEX = "/home/flancian/Burup/burup_media_types.json"

def main():
    with open(PHOTOS_MANIFEST, "r", encoding="utf-8") as f:
        all_photos = json.load(f)

    with open(MOTION_MANIFEST, "r", encoding="utf-8") as f:
        motion_items = json.load(f)

    dedicated_items = []
    if os.path.exists(DEDICATED_MANIFEST):
        with open(DEDICATED_MANIFEST, "r", encoding="utf-8") as f:
            dedicated_items = json.load(f)

    disk_videos = set(os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.join(VIDEOS_DIR, "*.mp4")))
    motion_ids_set = set(x["id"] for x in motion_items)
    dedicated_ids_set = set(x["id"] for x in dedicated_items)

    # Classification
    motion_ids = []
    dedicated_video_ids = []
    still_ids = []

    year_counts = Counter()

    for p in all_photos:
        pid = p["id"]
        label = p.get("label", "")
        
        # Extract year if possible
        year = "Unknown"
        for y in ["2026", "2025", "2024", "2023", "2022", "2021", "2020", "2019", "2018"]:
            if y in label:
                year = y
                break

        if pid in motion_ids_set and pid in disk_videos:
            motion_ids.append(pid)
            year_counts[(year, "motion")] += 1
        elif pid in dedicated_ids_set and pid in disk_videos:
            dedicated_video_ids.append(pid)
            year_counts[(year, "dedicated_video")] += 1
        else:
            still_ids.append(pid)
            year_counts[(year, "still")] += 1

    result = {
        "summary": {
            "total_items": len(all_photos),
            "motion_photos": len(motion_ids),
            "dedicated_videos": len(dedicated_video_ids),
            "still_photos": len(still_ids),
        },
        "motion_ids": motion_ids,
        "dedicated_video_ids": dedicated_video_ids,
        "still_ids": still_ids,
    }

    with open(OUTPUT_INDEX, "w", encoding="utf-8") as f:
        json.dump(result, f, indent=2)

    print(f"Generated {OUTPUT_INDEX}:")
    print(f"  Total archive items: {len(all_photos):,}")
    print(f"  Motion photos (with high-res photo + microvideo): {len(motion_ids):,} ({len(motion_ids)/len(all_photos)*100:.1f}%)")
    print(f"  Dedicated camera videos: {len(dedicated_video_ids):,} ({len(dedicated_video_ids)/len(all_photos)*100:.1f}%)")
    print(f"  Still photos (photo only): {len(still_ids):,} ({len(still_ids)/len(all_photos)*100:.1f}%)")
    
    print("\nDistribution by Year:")
    years = sorted(list(set(y for y, _ in year_counts.keys())), reverse=True)
    for y in years:
        m = year_counts[(y, "motion")]
        v = year_counts[(y, "dedicated_video")]
        s = year_counts[(y, "still")]
        tot = m + v + s
        print(f"  {y}: {tot:,} total | 📸 {s:,} still | 🎞️ {m:,} motion ({m/tot*100:.0f}%) | 🎬 {v} dedicated")

if __name__ == "__main__":
    main()
