import yt_dlp
import os

DOWNLOAD_DIR = "downloads"
os.makedirs(DOWNLOAD_DIR, exist_ok=True)

def get_formats(url):
    """Return available height options that actually exist for this video."""
    ydl_opts = {
        "quiet": True,
        "skip_download": True,
        "socket_timeout": 30,
        "retries": 5,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)
        heights = set()
        for f in info.get("formats", []):
            if f.get("height"):
                heights.add(f["height"])
        return info, sorted(heights)

def download_best(url, user_id):
    """Download the best available quality directly, no height selection.
    Used for platforms like Instagram where we skip the quality picker."""
    out_path = os.path.join(DOWNLOAD_DIR, f"{user_id}_best.mp4")
    ydl_opts = {
        "format": "bestvideo+bestaudio/best",
        "outtmpl": out_path,
        "merge_output_format": "mp4",
        "quiet": True,
        "socket_timeout": 30,
        "retries": 5,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    return out_path

def download_video(url, height, user_id):
    out_path = os.path.join(DOWNLOAD_DIR, f"{user_id}_{height}.mp4")
    # Fallback chain: try the exact requested height first, then any format
    # up to that height, then just the best available overall.
    # This fixes "Requested format is not available" on platforms like
    # Instagram/TikTok that don't always expose every resolution.
    format_selector = (
        f"bestvideo[height<={height}]+bestaudio/"
        f"best[height<={height}]/"
        f"bestvideo+bestaudio/"
        f"best"
    )
    ydl_opts = {
        "format": format_selector,
        "outtmpl": out_path,
        "merge_output_format": "mp4",
        "quiet": True,
        "socket_timeout": 30,
        "retries": 5,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    return out_path
