import time
from helpers.db import db_get_videos

# ───────── CACHE BUILDER ───────── #
def build_cache(start=None, end=None):
    """
    Build storage usage cache over an optional date range.
    start/end are date or datetime; end is inclusive by calendar day.
    """
    videos = db_get_videos(start=start, end=end)
    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.0
        for v in vids:
            try:
                total_gb += float(v.get("size", 0) or 0) / 1024.0
            except (ValueError, TypeError):
                # ignore bad rows
                continue

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

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