"""Main routes for home page and session management."""

from flask import Blueprint, flash, g, make_response, redirect, render_template, request, url_for

from ..database import db
from ..models import Upload
from ..services import SessionService

main_bp = Blueprint("main", __name__)


@main_bp.before_app_request
def load_session():
    """Load session from cookie before each request."""
    magic_phrase = request.cookies.get("magic_phrase")

    # Don't auto-create session - only load if cookie exists
    if magic_phrase and SessionService.validate_phrase(magic_phrase):
        # Try to load existing session
        session = SessionService.get_session_by_phrase(magic_phrase)
        if session:
            g.session = session
            g.new_session = False
        else:
            # Cookie exists but session not found/expired
            g.session = None
            g.new_session = False
    else:
        # No cookie - no session yet
        g.session = None
        g.new_session = False


@main_bp.after_app_request
def set_session_cookie(response):
    """Set session cookie after each request if new session."""
    if hasattr(g, "new_session") and g.new_session:
        response.set_cookie(
            "magic_phrase",
            g.session.magic_phrase,
            max_age=365 * 24 * 60 * 60,  # 30 days
            httponly=True,
            samesite="Lax",
        )
    return response


@main_bp.route("/")
def index():
    """Home page showing session info and recent uploads."""
    # Get recent uploads for this session (if session exists)
    uploads = []
    if g.session:
        uploads = (
            Upload.query.filter_by(session_id=g.session.id)
            .order_by(Upload.uploaded_at.desc())
            .limit(5)
            .all()
        )

    return render_template(
        "index.html", uploads=uploads, new_session=g.new_session
    )


@main_bp.route("/login", methods=["POST"])
def login():
    """Login to existing session using magic phrase."""
    magic_phrase = request.form.get("magic_phrase", "").strip().lower()

    if not magic_phrase:
        flash("Please enter a session phrase", "error")
        return redirect(url_for("main.index"))

    # Validate format
    if not SessionService.validate_phrase(magic_phrase):
        flash("Invalid session phrase format. Should be 4 words separated by hyphens.", "error")
        return redirect(url_for("main.index"))

    # Try to get session
    session = SessionService.get_session_by_phrase(magic_phrase)

    if not session:
        flash("Session not found or expired. Please check your session phrase.", "error")
        return redirect(url_for("main.index"))

    # Login successful - set cookie and redirect
    flash(f"Welcome back! Session '{session.magic_phrase}' reactivated and extended by 1 year.", "success")

    response = make_response(redirect(url_for("main.index")))
    response.set_cookie(
        "magic_phrase",
        session.magic_phrase,
        max_age=365 * 24 * 60 * 60,
        httponly=True,
        samesite="Lax",
    )

    return response


@main_bp.route("/thanks")
def thanks():
    """Thanks page acknowledging projects this tool relies on."""
    return render_template("thanks.html")


@main_bp.route("/logout", methods=["POST"])
def logout():
    """Logout from current session (clears cookie)."""
    confirmed = request.form.get("confirmed") == "true"

    if not confirmed:
        flash("Please confirm you have copied your session phrase before logging out.", "warning")
        return redirect(url_for("main.index"))

    # Clear session cookie
    response = make_response(redirect(url_for("main.index")))
    response.set_cookie(
        "magic_phrase",
        "",
        max_age=0,
        httponly=True,
        samesite="Lax",
    )

    flash("You have been logged out. Use your session phrase to log back in.", "info")

    return response
