from flask import Flask, request, send_file
from pytube import YouTube
import os
import subprocess

app = Flask(__name__)

@app.route('/download', methods=['GET'])
def download_video():
    url = request.args.get('url')
    resolution = request.args.get('resolution')

    if not url or not resolution:
        return "Missing 'url' or 'resolution' parameter", 400

    try:
        yt = YouTube(url)
        video_stream = yt.streams.filter(res=resolution, mime_type="video/mp4", progressive=False).first()
        audio_stream = yt.streams.filter(only_audio=True, mime_type="audio/mp4").first()

        if not video_stream or not audio_stream:
            return "Streams not found for given resolution", 404

        video_file = "video.mp4"
        audio_file = "audio.mp4"
        output_file = yt.title.replace(" ", "_").replace("/", "_") + "_1080p.mp4"

        video_stream.download(filename=video_file)
        audio_stream.download(filename=audio_file)

        command = [
            "ffmpeg",
            "-y",
            "-i", video_file,
            "-i", audio_file,
            "-c:v", "copy",
            "-c:a", "aac",
            "-strict", "experimental",
            output_file
        ]
        subprocess.run(command, check=True)

        return send_file(output_file, as_attachment=True)

    except Exception as e:
        return f"Error: {str(e)}", 500

    finally:
        for f in ["video.mp4", "audio.mp4", output_file]:
            if os.path.exists(f):
                os.remove(f)

if __name__ == '__main__':
    app.run(debug=True, port=5001)
