from yt_dlp import YoutubeDL

from ..utils._path_util import resolve_path

class VideoDownloader:
    def __init__(self, download_store, cookies_txt_path: str | None = None):
        self._download_store = resolve_path(download_store)
        self._download_store.mkdir(parents=True, exist_ok=True)

        self._ydl_opts = {
            # Auth
            "cookiefile": cookies_txt_path or "cookies.txt",

            # JS challenge (YouTube 2025)
            "js_runtimes": {
                "node": {}
            },
            "extractor_args": {
                "youtube": {
                    "player_skip": [],
                }
            },
            "remote_components": ["ejs:github"],

            # Format: MP4 <= 360p
            "format": "best[ext=mp4][height<=360]",

            # Output
            "outtmpl": f"{self._download_store}/%(channel)s/%(channel)s ｜ %(title)s ｜ [%(id)s].%(ext)s",

            "windowsfilenames": True,
            "restrictfilenames": False,

            # Network stability
            "force_ipv4": True,
            "noplaylist": True,

            # Logging
            "quiet": False,
            "no_warnings": False,
        }

    def download(self, yt_url):
        with YoutubeDL(self._ydl_opts) as ydl:
            ydl.download([yt_url])
