import logging
import os
import uuid
from flask import Flask, render_template, request, session

# Only used for the main.process function, but it feels right to have that over just "process"
import main

app = Flask(__name__, static_folder="website/static", template_folder="website")
app.secret_key = os.urandom(24)  # Necessary for using sessions


def create_session() -> str:
    """
    Create a new session by generating a UUID and ensuring it does not collide
    with an existing session in the user_streams global dictionary.

    Returns:
        str: A unique session ID.
    """
    return uuid.uuid4().hex


@app.get("/")
def home():
    """
    Render the home page and initialize a session.

    Returns:
        Response: The rendered home page with a unique session id.
    """
    session_id = create_session()
    session["id"] = session_id
    logging.info(f"Home page accessed. Assigned initial session ID: {session_id}")
    return render_template("index.html", session_id=session_id)


@app.post("/process-url")
def process_url():
    """
    Accept a YouTube URL (from a form submission), initialize the session if necessary,
    and trigger the transcript retrieval and AI processing.

    Returns:
        Response: The results of processing the url.
    """
    session_id = session.get("id")
    if not session_id:
        session_id = create_session()
        session["id"] = session_id
        logging.info(f"No existing session. Created new session ID: {session_id}")
    url = request.form["url"]
    logging.info(f"Received URL for processing from session {session_id}: {url}")
    # Before I had process return stuff in the form of (success: bool, msg: str, status: int)
    # I don't know why I was doing all that back then, it's not like it was a library or anything
    # I planned on using on other projects...
    return main.process(url, session_id)


if __name__ == "__main__":
    logging.info("Starting Flask application.")
    # Running with threaded=True to handle multiple requests concurrently.
    app.run(debug=True, threaded=True)
