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

BASE_DIR = Path("/var/lib/ffplayout/tv-media/Shuffle-for-tv")
STAGING = BASE_DIR / "Staging"
STAGING.mkdir(exist_ok=True)

with open("peertube_communitymediavideos.json") as f:
    community = json.load(f)
with open("peertube_newellijay.json") as f:
    newellijay = json.load(f)

all_videos = community + newellijay

to_download = []
for v in all_videos:
    title = v.get("title", "").lower()
    is_live = v.get("is_live") is True or v.get("live_status") == "is_live" or "on air" in title
    if is_live:
        print(f"Skipping LIVE stream: {v.get('title')}")
        continue
    if any(skip in title for skip in ["weather", "new ellijay news", "podcast", "observers", "kspr"]):
        continue
    to_download.append(v.get("webpage_url"))

print(f"Downloading {len(to_download)} high-priority non-live videos...")
for url in to_download:
    cmd = [
        "yt-dlp",
        "--download-archive", str(BASE_DIR / "downloaded.txt"),
        "--no-live-from-start",
        "-o", str(STAGING / "%(title)s.%(ext)s"),
        url
    ]
    subprocess.run(cmd)

print("Download complete.")
