import subprocess
import shutil
from pathlib import Path

# In-memory cache: url -> [video_id, ...]
playlist_cache = {}


def yt_extract(url):
    """Kör yt-dlp och returnera (ids, total_seconds). Kastar undantag vid fel."""
    ytdlp = shutil.which('yt-dlp') or '/home/mrfox/.local/bin/yt-dlp'
    if not ytdlp or not Path(ytdlp).exists():
        raise RuntimeError('yt-dlp är inte installerat')
    result = subprocess.run(
        [ytdlp, '--flat-playlist', '--print', 'id', '--print', '%(duration)s',
         '--no-warnings', url],
        capture_output=True, text=True, timeout=60
    )
    lines = [l.strip() for l in result.stdout.splitlines() if l.strip()]
    # Rader alternerar: id, duration, id, duration, ...
    ids, total_seconds = [], 0
    for i in range(0, len(lines) - 1, 2):
        ids.append(lines[i])
        try:
            total_seconds += int(lines[i + 1])
        except ValueError:
            pass
    if not ids:
        raise RuntimeError(result.stderr[:300] or 'Inga videos hittades')
    return ids, total_seconds
