import os
import yt_dlp

def download_youtube_video(video_url: str, save_path: str = "downloads"):
    """
    Downloads a YouTube video in the best available video and audio quality (HD if available).

    Args:
        video_url (str): URL of the YouTube video.
        save_path (str): Directory to save the downloaded video.
    """
    os.makedirs(save_path, exist_ok=True)  # Ensure save path exists

    ydl_opts = {
        # Download best video + best audio and merge them
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best',
        'outtmpl': f'{save_path}/%(title)s.%(ext)s',  # Output template
        'merge_output_format': 'mp4',  # Merge into mp4
        'noplaylist': True,  # Only single video
        'quiet': False,  # Show progress
        'ignoreerrors': True,
        # JS runtime for YouTube challenges
        'js_runtimes': {'node': {}},
        # Use remote EJS components to solve JS challenges
        'remote_components': ['ejs:github'],
        'http_headers': {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
        },
    }

    try:
        print(f"Downloading video from URL: {video_url}")
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([video_url])
        print(f"✅ Video downloaded successfully into folder: {save_path}")
    except Exception as e:
        print(f"❌ Error downloading video: {e}")


if __name__ == "__main__":
    video_url = input("Enter the YouTube video URL: ").strip()
    save_path = input("Enter the save path (or press Enter for default 'downloads'): ").strip() or "downloads"
    
    download_youtube_video(video_url, save_path)
