from funcs import process_videos, group_videos, match_data_to_video_fast, get_all_videos, get_all_data
from flask import Flask, render_template
import os
from collections import defaultdict

app = Flask(__name__)

SCAN_DIRS = [
    "E:/streamaster/downloaded/",
    "U:/encoded",
    "U:/count_sorted"
]

DATA_DIRS = [
    "E:/streamaster/data",
    "E:/streamaster/downloaded",
]

# ----------- Data Processing -----------
def load_video_data():
    videos = []
    for d in SCAN_DIRS:
        videos += get_all_videos(d)

    data = []
    for d in DATA_DIRS:
        data += get_all_data(d)

    parsed_videos, unmatched = match_data_to_video_fast(videos, data)
    parsed_videos = process_videos(parsed_videos)
    video_data = group_videos(parsed_videos, sort_by="count", order="desc")
    return video_data

def compute_analytics(video_data):
    storage_usage = defaultdict(lambda: {"total_size": 0, "video_count": 0})
    per_video_sizes = {}

    for (username, platform), vids in video_data.items():
        total_size_gb = sum(v['size'] for v in vids) / 1024  # Convert MB to GB
        avg_size_gb = (total_size_gb / len(vids)) if vids else 0

        storage_usage[(username, platform)]["total_size"] += total_size_gb
        storage_usage[(username, platform)]["video_count"] += len(vids)
        per_video_sizes[(username, platform)] = avg_size_gb

    return storage_usage, per_video_sizes

# ----------- Flask Routes -----------
@app.route("/")
def analytics_dashboard():
    video_data = load_video_data()
    storage_usage, per_video_sizes = compute_analytics(video_data)

    # Sort by total storage used
    sorted_usage = sorted(storage_usage.items(), key=lambda x: x[1]["total_size"], reverse=True)

    return render_template("analytics.html",
                           storage_usage=sorted_usage,
                           avg_sizes=per_video_sizes)

if __name__ == "__main__":
    app.run(debug=True)