import yt_dlp
import sys
import os

def download_video(url, output_format):
    # Define file extension based on format
    ext = "mp4" if output_format == "mp4" else "mp3"

    # Define options for yt_dlp
    ydl_opts = {
        'outtmpl': f'downloaded_video.%(ext)s',
    }

    # Set download format
    if output_format == "mp3":
        ydl_opts.update({
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        })
    else:  # default to mp4
        ydl_opts.update({
            'format': 'bestvideo+bestaudio/best',
            'merge_output_format': 'mp4'
        })

    # Start downloading
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# Main execution
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python script.py <YouTube_URL> <mp4|mp3>")
    else:
        video_url = sys.argv[1]
        format_type = sys.argv[2].lower()

        if format_type not in ['mp4', 'mp3']:
            print("Error: Format must be 'mp4' or 'mp3'")
        else:
            download_video(video_url, format_type)
