from flask import Flask, render_template, request, redirect, url_for, flash
from download import download_youtube_video
import os

app = Flask(__name__)
app.secret_key = "supersecretkey"  # Needed for flash messages

DOWNLOAD_FOLDER = os.path.join(os.getcwd(), "downloads")
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        url = request.form.get("video_url").strip()
        if not url:
            flash("❌ Please enter a YouTube URL!", "error")
            return redirect(url_for("index"))

        try:
            download_youtube_video(url, save_path=DOWNLOAD_FOLDER)
            flash("✅ Video downloaded successfully!", "success")
        except Exception as e:
            flash(f"❌ Error: {e}", "error")
        return redirect(url_for("index"))

    return render_template("index.html")


if __name__ == "__main__":
    app.run(debug=True)
