from flask import Flask, Response, request, stream_with_context
import yt_dlp
import subprocess
import re

app = Flask(__name__)

@app.route('/')
def index():
    return '''
    <html>
    <head>
        <title>Simple Video Downloader</title>
        <style>
            body {
                background: #f9f9f9;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
            }
            .container {
                background: #ffffff;
                border-radius: 10px;
                padding: 40px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                text-align: center;
                width: 100%;
                max-width: 400px;
            }
            h1 {
                font-size: 22px;
                margin-bottom: 20px;
                color: #333;
            }
            input, select, button {
                width: 100%;
                padding: 12px;
                margin: 10px 0;
                border-radius: 6px;
                border: 1px solid #ccc;
                font-size: 16px;
            }
            button {
                background-color: #007BFF;
                color: white;
                border: none;
                cursor: pointer;
                transition: background-color 0.3s ease;
            }
            button:hover {
                background-color: #0056b3;
            }
            .footer {
                margin-top: 20px;
                font-size: 12px;
                color: #999;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Video & Audio Downloader</h1>
            <form action="/download" method="get">
                <input name="url" type="url" placeholder="Paste YouTube or Instagram URL" required>
                <select name="format">
                    <option value="mp4">Download as MP4</option>
                    <option value="mp3">Download as MP3</option>
                    <option value="instagram">Instagram Reel (MP4)</option>
                </select>
                <button type="submit">Start Download</button>
            </form>
            <div class="footer">Supports YouTube & Instagram</div>
        </div>
    </body>
    </html>
    '''

@app.route('/download')
def download():
    url = request.args.get('url')
    fmt = request.args.get('format', 'mp4')

    try:
        with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
            info = ydl.extract_info(url, download=False)
            title = re.sub(r'[^\w\-_\. ]', '_', info.get('title', 'download'))
            extension = 'mp4' if fmt in ['mp4', 'instagram'] else 'mp3'
            filename = f"{title}.{extension}"
    except Exception as e:
        return f"<h2>Error fetching video info: {str(e)}</h2>"

    # yt-dlp command setup
    ytdlp_cmd = [
        "yt-dlp",
        url,
        "-f", "bestaudio/best" if fmt == "mp3" else "best",
        "-o", "-",  # output to stdout
    ]

    if fmt == "mp3":
        ytdlp_cmd += [
            "--extract-audio",
            "--audio-format", "mp3",
            "--audio-quality", "192K",
        ]

    def generate():
        process = subprocess.Popen(ytdlp_cmd, stdout=subprocess.PIPE)
        while True:
            chunk = process.stdout.read(1024 * 256)
            if not chunk:
                break
            yield chunk
        process.stdout.close()
        process.wait()

    return Response(
        stream_with_context(generate()),
        mimetype='application/octet-stream',
        headers={"Content-Disposition": f'attachment; filename="{filename}"'}
    )

if __name__ == '__main__':
    app.run(debug=True)
