"""
Development authentication routes for StarPunk

WARNING: These routes provide instant authentication bypass for local development.
They are ONLY registered when DEV_MODE=true and return 404 otherwise.

This file contains routes that should never be accessible in production.
"""

from flask import Blueprint, abort, current_app, flash, redirect, url_for

from starpunk.dev_auth import create_dev_session, is_dev_mode

# Create blueprint
bp = Blueprint("dev_auth", __name__, url_prefix="/dev")


@bp.before_request
def check_dev_mode():
    """
    Security guard: Block all dev auth routes if DEV_MODE is disabled

    This executes before every request to dev auth routes.
    Returns 404 if DEV_MODE is not explicitly enabled.

    Returns:
        None if DEV_MODE is enabled, 404 abort otherwise

    Security:
        This is the primary safeguard preventing dev auth in production.
        Even if routes are accidentally registered, they will return 404.
    """
    if not is_dev_mode():
        # Return 404 - dev routes don't exist in production
        abort(404)


@bp.route("/login", methods=["GET", "POST"])
def dev_login():
    """
    Instant development login (no authentication required)

    WARNING: This creates an authenticated session WITHOUT any verification.
    Only accessible when DEV_MODE=true.

    Returns:
        Redirect to admin dashboard with session cookie set

    Sets:
        session cookie (HttpOnly, NOT Secure in dev mode, 30 day expiry)

    Logs:
        WARNING: Logs that dev authentication was used

    Security:
        - Blocked by before_request if DEV_MODE=false
        - Logs warning on every use
        - Creates session for DEV_ADMIN_ME identity
    """
    # Get configured dev admin identity
    me = current_app.config.get("DEV_ADMIN_ME")

    if not me:
        flash("DEV_MODE misconfiguration: DEV_ADMIN_ME not set", "error")
        return redirect(url_for("auth.login_form"))

    # Create session without authentication
    session_token = create_dev_session(me)

    # Create response with redirect
    response = redirect(url_for("admin.dashboard"))

    # Set session cookie (NOT secure in dev mode)
    response.set_cookie(
        "starpunk_session",
        session_token,
        httponly=True,
        secure=False,  # Allow HTTP in development
        samesite="Lax",
        max_age=30 * 24 * 60 * 60,  # 30 days
    )

    flash("DEV MODE: Logged in without authentication", "warning")
    return response
