import time
from helpers.db import db_get_videos
# from helpers.thumbnails import generate_thumbnails_for_videos  # optional

# ───────── CACHE BUILDER ───────── #
def build_cache():
    videos = db_get_videos()
    grouped = {}

    for v in videos:
        key = (v["username"], v["platform"])
        grouped.setdefault(key, []).append(v)

    storage_usage, avg_sizes, video_map = {}, {}, {}

    for (username, platform), vids in grouped.items():
        key = f"{username}::{platform}"

        total_gb = 0
        for v in vids:
            try:
                total_gb += float(v.get("size", 0) or 0) / 1024
            except ValueError:
                print(f"⚠️ Invalid size for video {v.get('video_id')}: {v.get('size')}")

        storage_usage[key] = {
            "total_size": total_gb,
            "video_count": len(vids)
        }
        avg_sizes[key] = total_gb / len(vids) if vids else 0

        video_map[key] = vids

    # Thumbnail generation is optional, uncomment if you want it auto-built:
    # generate_thumbnails_for_videos(videos)

    return {
        "timestamp": time.time(),
        "videos": video_map,
        "storage_usage": storage_usage,
        "avg_sizes": avg_sizes
    }