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

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 get_local_videos():
    videos = {}
    for f in BASE_DIR.rglob("*.mp4"):
        title = f.stem.lower()
        duration = None
        try:
            dur = subprocess.run(["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", str(f)], 
                               capture_output=True, text=True, timeout=5)
            duration = round(float(dur.stdout.strip()), 1) if dur.stdout.strip() else None
        except:
            pass
        videos[title] = {"path": str(f.relative_to(BASE_DIR)), "duration": duration}
    return videos

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

print("=== Peertube vs Local Comparison ===")
local = get_local_videos()
peertube = get_peertube_videos()

print(f"\nLocal videos found: {len(local)}")
print(f"Peertube videos found: {len(peertube)}\n")

missing = []
for video in peertube:
    title_lower = video["title"].lower()
    found = False
    for local_title, data in local.items():
        if title_lower in local_title or local_title in title_lower:
            if video["duration"] and data["duration"]:
                if abs(video["duration"] - data["duration"]) < 3.0:
                    print(f"✓ Present: {video['title']}")
                    found = True
                    break
    if not found:
        missing.append(video)

print(f"\n=== Missing / New on Peertube: {len(missing)} ===")
for v in missing:
    print(f"  • {v['title']} ({v.get('duration')}s)")

print("\nRun this script again after new videos are uploaded to see updates.")
