#!/usr/bin/env python3
import subprocess
import json
from pathlib import Path
import re

BASE_DIR = Path("/var/lib/ffplayout/tv-media/Shuffle-for-tv")
SOURCES = [
    "https://communitymedia.video/c/communitymediavideos/videos",
    "https://communitymedia.video/a/video@vod.newellijay.tv/video-channels"
]

def clean_title(title):
    return re.sub(r'[^a-z0-9]', '', title.lower())

def get_local_titles():
    titles = {}
    for f in BASE_DIR.rglob("*.mp4"):
        clean = clean_title(f.stem)
        titles[clean] = str(f.relative_to(BASE_DIR))
    return titles

def get_peertube_videos():
    videos = []
    for url in SOURCES:
        print(f"Fetching all videos from: {url}")
        try:
            cmd = ["yt-dlp", "--flat-playlist", "--dump-json", url]
            output = subprocess.check_output(cmd, text=True, timeout=120)
            for line in output.strip().split("\n"):
                if line.strip():
                    info = json.loads(line)
                    videos.append({
                        "title": info.get("title", "Unknown"),
                        "clean_title": clean_title(info.get("title", "")),
                        "url": info.get("webpage_url")
                    })
        except Exception as e:
            print(f"Error fetching {url}: {e}")
    return videos

print("Scanning local files...")
local = get_local_titles()
print(f"Found {len(local)} local videos.")

print("\nFetching ALL Peertube videos...")
peertube = get_peertube_videos()
print(f"Found {len(peertube)} videos on Peertube.")

print("\n=== Missing or New Videos ===")
missing = []
for v in peertube:
    if v["clean_title"] not in local:
        missing.append(v["title"])
        print(f"  • {v['title']}")

print(f"\nTotal missing/new: {len(missing)}")
print("Run this script again after new uploads to see updates.")
