import tempfile
from collections.abc import Iterator
from pathlib import Path

import yt_dlp
from loguru import logger
from pydantic import BaseModel


class DownloadClosedCaptionsSvc(BaseModel):
    @staticmethod
    def run(youtube_url: str, sub_lang: str = "es") -> Iterator[Path]:
        """Download closed captions from a yt video and save it to a temp file

        Args:
            youtube_url: URL of the YouTube video
            sub_lang: Language code for the subtitles (default: "es" for Spanish)

        Returns:
            Path: Path to the downloaded subtitles file

        Raises:
            ValueError: If subtitles are not available in the requested language
        """
        temp_dir = Path(tempfile.mkdtemp())
        logger.info(f"Downloading subtitles for {youtube_url} to {temp_dir}")
        ydl_opts = {
            "skip_download": True,
            "writesubtitles": True,
            "writeautomaticsub": True,
            "subtitleslangs": [sub_lang],
            "subtitlesformat": "vtt",
            "cookiesfrombrowser": ("firefox",),
            "paths": {"home": str(temp_dir)},
            "quiet": True,
        }

        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download([youtube_url])
                return temp_dir.glob(f"*.{sub_lang}.vtt")

        except yt_dlp.utils.DownloadError as exc:
            raise ValueError(f"Failed to download subtitles: {exc!s}") from exc
