"""Auth routes — request magic link, consume magic link, log out.

The visible UI surface is intentionally small for v1:
  GET  /login            — form (email input + submit)
  POST /login            — accepts email, mints + emails magic link
  GET  /auth/<token>     — consume the token, set session, redirect
  POST /logout           — clear session, redirect home

The /my-builds page (which is the destination for most magic-link
flows) lives in a separate blueprint to keep concerns split.
"""

from __future__ import annotations

from flask import (Blueprint, current_app, redirect, render_template, request,
                   url_for)

from .. import auth

bp = Blueprint("auth", __name__)


def safe_next(next_url: str, fallback: str = "/my-builds") -> str:
    """Open-redirect guard for ?next= params. Only same-origin paths
    are allowed back through. Rejects:
      - empty / missing values
      - anything not starting with '/'
      - '//evil.com' (protocol-relative URLs — browsers treat as absolute)
      - '/\\evil.com' (Safari historically normalized '\\' → '/', so
        '/\\evil.com' could resolve to '//evil.com' → absolute redirect;
        security finding M2)
    Returns either the validated `next_url` or `fallback`."""
    if not next_url or not isinstance(next_url, str):
        return fallback
    if not next_url.startswith("/"):
        return fallback
    if next_url.startswith("//"):
        return fallback
    if next_url.startswith("/\\"):
        return fallback
    return next_url


@bp.route("/login", methods=["GET", "POST"])
def login_view():
    """Email entry form + submission. On POST we ALWAYS show the
    "check your email" confirmation, even if the email was invalid or
    the magic-link send failed — so an attacker can't enumerate which
    emails have accounts by submitting different addresses and
    watching for different responses.

    `next=` query param survives the round trip — it's stamped into
    the magic link so the post-consume redirect lands the user
    where they were trying to go (e.g. /my-builds)."""
    next_url = request.values.get("next") or "/my-builds"
    if request.method == "POST":
        email = request.form.get("email", "").strip()
        # Honeypot: a real browser leaves the off-screen `website` field
        # empty; a form-spam bot fills it. If it's non-empty, silently drop
        # the request — render the SAME confirmation page (no enumeration
        # signal) but send NO email and write NO magic_link row, so bots
        # can't use us to mail third parties or pollute the table.
        if request.form.get("website", "").strip():
            current_app.logger.info("login honeypot tripped (bot); dropped")
            return render_template("auth/check_email.html",
                                   email=email, next=next_url)
        # Best-effort send; auth.request_magic_link tolerates bad
        # input silently to avoid enumeration. Always render the same
        # confirmation page.
        auth.request_magic_link(email, redirect_to=next_url)
        return render_template("auth/check_email.html",
                               email=email, next=next_url)
    return render_template("auth/login.html", next=next_url)


@bp.route("/auth/<token>")
def consume(token):
    """Click target for the magic link. Consumes the token, logs the
    user in, redirects. Open-redirect guard on `next`: only same-site
    paths allowed (must start with `/` and not `//`)."""
    user = auth.consume_magic_link(token)
    if not user:
        return render_template("auth/invalid_link.html"), 400
    auth.login(user)
    return redirect(safe_next(request.args.get("next")))


@bp.route("/auth/code", methods=["POST"])
def consume_code_view():
    """Companion to /auth/<token> for users who entered the 6-digit
    code on the 'check your email' page instead of clicking the link.
    Same end state: session set, redirect to next or /my-builds.

    Now bound to email — the form's hidden email field is required for
    the consume to even attempt a match. Closes the unbounded brute-
    force surface previously present on this endpoint (security review
    finding C1, [[golive-requirements-doc]] section G)."""
    code = (request.form.get("code") or "").strip()
    email = (request.form.get("email") or "").strip()
    next_url = request.form.get("next") or "/my-builds"
    user = auth.consume_code(code, email)
    if not user:
        return render_template("auth/check_email.html",
                               email=email,
                               next=next_url,
                               code_error="That code didn't work. It "
                                          "may be expired, already used, "
                                          "or mistyped. After 5 wrong "
                                          "attempts the link is burned. "
                                          "Request a fresh one if so."), 400
    auth.login(user)
    return redirect(safe_next(next_url))


@bp.route("/logout", methods=["POST"])
def logout():
    auth.logout()
    return redirect("/")
