"""Email-magic-link auth for site-ng.

No passwords. Identity is an email address. To establish a session:
the user enters their email → we mint a single-use token, store it
in `magic_link`, email a link `/auth/<token>` → click consumes the
token, sets `session['user_id']`, sticks for ~30-90 days on that
browser. Fresh link required to re-establish session on a different
browser / after cookie clear.

This module is **transport-agnostic** — it generates / consumes
tokens, manipulates the session, and asks `mail.send_mail` to deliver
the link. The mail module decides how (console-log in dev, sendmail/
SMTP in prod).

See also:
  - site-ng/docs/build-feature-design.md "Identity model" section
  - memory: feature-site-share-builds (locked design 2026-05-25)
"""

from __future__ import annotations

import logging
import secrets
from datetime import datetime, timedelta
from typing import Optional

from flask import current_app, flash, request, session, url_for

from . import mail
from .db import get_db

logger = logging.getLogger(__name__)

# Token sizing: 32 chars of url-safe alphabet (~190 bits of entropy).
# Stored as the URL slug `/auth/<token>` and as the `magic_link.token`
# unique key.
_TOKEN_BYTES = 24  # secrets.token_urlsafe(24) → 32 chars

# Default lifetimes — overridable via app config.
_LINK_TTL_MIN = 30          # MAIL_LINK_TTL_MIN
_SESSION_TTL_DAYS = 60      # MAIL_SESSION_TTL_DAYS

# Magic-link send rate limits (per email; bounds email-bombing + SMTP abuse).
# Three layers, all silent (the login view shows the same neutral "check your
# email" page regardless, so throttling leaks nothing — no enumeration):
#   - per-email: protects a victim's inbox (keyed on magic_link.created).
#   - per-IP: stops a script walking an email list from one host (keyed on the
#     magic_link.ip column; degrades off if that column isn't present).
#   - global: a site-wide circuit breaker, caps blast radius vs IP rotation.
_MAX_LINKS_PER_HOUR = 5        # max magic-link emails per address per rolling hour
_LINK_COOLDOWN_SEC = 45        # min gap between sends to the same address
_MAX_LINKS_PER_IP_HOUR = 30    # max sends per source IP per rolling hour
_GLOBAL_LINKS_PER_HOUR = 200   # site-wide cap per rolling hour (circuit breaker)

# Cached: does magic_link have the optional `ip` column? Lets per-IP throttling
# (and the ip insert) degrade gracefully on a DB without it, so login never
# breaks regardless of deploy/DDL ordering or which site's DB we're on.
_HAS_IP_COL = None


def _client_ip() -> str:
    """Client IP via the RIGHT-most X-Forwarded-For hop — the trusted proxy
    added it; the left-most entry is client-spoofable (security finding M1)."""
    xff = request.headers.get("X-Forwarded-For", "")
    return (xff.rsplit(",", 1)[-1].strip() if xff else "") \
        or (request.remote_addr or "unknown")


def _magic_link_has_ip(cur) -> bool:
    # Probe via the table's own SELECT (a priv the app user definitely has) so
    # detection doesn't depend on information_schema visibility. Errors -> absent.
    global _HAS_IP_COL
    if _HAS_IP_COL is None:
        try:
            cur.execute("SELECT ip FROM magic_link LIMIT 0")
            cur.fetchall()
            _HAS_IP_COL = True
        except Exception:
            _HAS_IP_COL = False
    return _HAS_IP_COL


# --------------------------------------------------------------------------- #
# user lookup
# --------------------------------------------------------------------------- #
def _normalize_email(email: str) -> str:
    """Lowercase + strip. Mailservers are case-insensitive on the
    local part in practice; the lowercase normalization stops a user
    from accidentally creating two accounts via case-variant addresses
    (Mike@example.com vs mike@example.com)."""
    return (email or "").strip().lower()


def _validate_email(email: str) -> Optional[str]:
    """Normalize + light-validate. Returns the normalized email or None.
    Light validation only: presence of '@', no spaces. The magic-link
    send is the canonical deliverability test."""
    email = _normalize_email(email)
    if not email or "@" not in email or " " in email:
        return None
    return email


def get_or_create_user(email: str) -> Optional[dict]:
    """Look up an `app_user` by email; create one if it doesn't exist.
    Returns the user dict or None if `email` is empty / invalid.

    Called from the consume_* functions ONLY (post-confirmation). NOT
    called by request_magic_link any more — see security finding L2
    [[golive-requirements-doc]]: we used to eagerly create app_user
    on every /login attempt, which (a) recorded every typo or probe in
    the table forever, (b) let an unauthenticated endpoint bloat the
    table via spam. Now the row only materializes once someone proves
    they control the email (by consuming a link or code)."""
    email = _validate_email(email)
    if not email:
        return None
    cur = get_db().cursor()
    cur.execute("SELECT * FROM app_user WHERE email=%s", (email,))
    row = cur.fetchone()
    if row:
        return row
    cur.execute(
        "INSERT INTO app_user (email, created) VALUES (%s, NOW())",
        (email,))
    user_id = cur.lastrowid
    get_db().commit()
    cur.execute("SELECT * FROM app_user WHERE id=%s", (user_id,))
    return cur.fetchone()


def get_user_by_id(user_id: int) -> Optional[dict]:
    if not user_id:
        return None
    cur = get_db().cursor()
    cur.execute("SELECT * FROM app_user WHERE id=%s", (int(user_id),))
    return cur.fetchone()


# --------------------------------------------------------------------------- #
# magic links
# --------------------------------------------------------------------------- #
def request_magic_link(email: str,
                       redirect_to: Optional[str] = None) -> Optional[str]:
    """Mint a fresh magic-link token for `email` and email it.
    Returns the token (mainly for tests / dev logging — the email
    delivery is the user-facing path). Returns None if `email` is
    invalid.

    Does NOT create an `app_user` row — the row only materializes on
    successful consume. The magic_link table itself carries the email
    until that point. Security finding L2 ([[golive-requirements-doc]]):
    eagerly creating app_user on every /login attempt recorded every
    typo and every attacker probe in the table forever AND let an
    unauthenticated endpoint bloat the table via spam.

    Any unconsumed prior links for the same email are invalidated by
    setting their `consumed_at` to now — prevents stale-link-as-
    backdoor (if a user requests a fresh link, the old one can't
    still log them in)."""
    email = _validate_email(email)
    if not email:
        return None
    cfg = current_app.config
    ttl = int(cfg.get("MAIL_LINK_TTL_MIN", _LINK_TTL_MIN))

    # Rate limiting (all silent — return None lands on the same neutral page).
    ip = _client_ip()
    rl = get_db().cursor()
    has_ip = _magic_link_has_ip(rl)

    # (1) Global circuit breaker — caps total sends/hour site-wide. Catches
    #     IP-rotated / distributed abuse that per-IP can't, by bounding the
    #     blast radius. Generous so a legit spike never starves real users.
    rl.execute("SELECT COUNT(*) AS n FROM magic_link "
               "WHERE created > NOW() - INTERVAL 1 HOUR")
    if ((rl.fetchone() or {}).get("n") or 0) >= _GLOBAL_LINKS_PER_HOUR:
        current_app.logger.warning("magic-link GLOBAL cap hit; throttling sends")
        return None

    # (2) Per-email — protects a victim's inbox (hourly cap + short cooldown).
    rl.execute(
        "SELECT COUNT(*) AS n, "
        "       SUM(created > NOW() - INTERVAL %s SECOND) AS recent "
        "FROM magic_link "
        "WHERE email=%s AND created > NOW() - INTERVAL 1 HOUR",
        (_LINK_COOLDOWN_SEC, email))
    row = rl.fetchone() or {}
    if (row.get("n") or 0) >= _MAX_LINKS_PER_HOUR or (row.get("recent") or 0) > 0:
        current_app.logger.info(
            "magic-link throttled (email) for %s (hour=%s, cooldown=%s)",
            email, row.get("n"), bool(row.get("recent")))
        return None

    # (3) Per-IP — stops one host walking an email list (needs the ip column).
    if has_ip and ip and ip != "unknown":
        rl.execute("SELECT COUNT(*) AS n FROM magic_link "
                   "WHERE ip=%s AND created > NOW() - INTERVAL 1 HOUR", (ip,))
        if ((rl.fetchone() or {}).get("n") or 0) >= _MAX_LINKS_PER_IP_HOUR:
            current_app.logger.warning("magic-link throttled (ip) for %s", ip)
            return None

    token = secrets.token_urlsafe(_TOKEN_BYTES)
    # 6-digit human-typeable code accompanying the long token. Either
    # consumes the same row. Provides a recovery path if the magic
    # link in the email isn't directly clickable (mobile vs desktop
    # mismatch, link mangled by the mail client, "the email is across
    # the room"). UX same as Slack/Notion sign-in.
    code = f"{secrets.randbelow(1_000_000):06d}"
    cur = get_db().cursor()
    # Invalidate prior unconsumed links for this EMAIL. We use email
    # (not user_id) because at this point the user_id may not exist
    # yet — the app_user row doesn't get created until consume.
    cur.execute(
        "UPDATE magic_link SET consumed_at=NOW() "
        "WHERE email=%s AND consumed_at IS NULL",
        (email,))
    if has_ip:
        cur.execute(
            "INSERT INTO magic_link "
            "  (email, ip, token, code, created, expires_at) "
            "VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL %s MINUTE)",
            (email, ip, token, code, ttl))
    else:
        cur.execute(
            "INSERT INTO magic_link "
            "  (email, token, code, created, expires_at) "
            "VALUES (%s, %s, %s, NOW(), NOW() + INTERVAL %s MINUTE)",
            (email, token, code, ttl))
    get_db().commit()

    # Construct the click-through URL. Honor app config's URL root if
    # set (for emails sent in cron jobs without a request context),
    # else compose from the current request.
    root = cfg.get("PUBLIC_URL_ROOT") or request.host_url.rstrip("/")
    path = "/auth/" + token
    if redirect_to:
        from urllib.parse import quote
        path += "?next=" + quote(redirect_to, safe="/?=&")
    link_url = root + path

    _send_link_email(email, link_url, code, ttl)
    return token


def _send_link_email(to: str, link_url: str, code: str,
                     ttl_min: int) -> None:
    body = (
        "Sign in to ARPartsFinder. Two ways:\n\n"
        "1. Click this link from this device:\n"
        f"   {link_url}\n\n"
        "2. Or enter this 6-digit code on the 'Check your email'\n"
        f"   page:   {code}\n\n"
        f"Both options expire in {ttl_min} minutes. The link or code is "
        "single-use; once consumed it can't be reused.\n\n"
        "If you didn't request this, ignore this email. No account "
        "was created or accessed.\n\n"
        "arpartsfinder.com\n")
    mail.send_mail(to, "Sign in to ARPartsFinder", body)


# Maximum failed code attempts per active magic-link row before that
# row is burned (treated as if consumed). Five gives users a margin for
# fat-fingering while keeping a brute-forcer to one-in-200,000 odds
# even against a known email (5/10^6). With email binding (below) the
# attacker also has to know the email — so the brute-force keyspace is
# per-user, not global.
_MAX_CODE_ATTEMPTS = 5


def consume_code(code: str, email: str) -> Optional[dict]:
    """Sister of consume_magic_link — consumes a magic-link row by
    its 6-digit code instead of the long URL token.

    Bound to email: the SQL requires that the code matches a magic_link
    row whose email column matches the supplied email. Without this
    binding, /auth/code is effectively a global 6-digit brute-force
    surface (1M keyspace shared across all active codes). With binding,
    the attacker has to know AND target a specific email — making
    per-user rate-limiting meaningful. See security finding C1.

    On success: materializes the app_user row if it doesn't exist yet
    (deferred-creation per security finding L2) and backfills
    magic_link.user_id for forensics / future "all magic links by user"
    queries.

    Lockout: every failed (code, email) attempt increments
    failed_attempts on EVERY unconsumed link for that email. Past
    _MAX_CODE_ATTEMPTS, the link is treated as if consumed (skipped
    by the WHERE clause below) — so a brute-forcer gets at most 5
    guesses per ttl-window per email.

    Same single-use semantics as the original."""
    if not code or not code.isdigit() or len(code) != 6:
        return None
    email = _validate_email(email)
    if not email:
        return None
    cur = get_db().cursor()

    # Atomic consume: must match (code, email), unconsumed, unexpired,
    # AND not over the per-link attempt cap. We key on email (NOT
    # user_id) because the app_user row may not exist yet — deferred
    # creation is the L2 fix.
    cur.execute(
        "UPDATE magic_link SET consumed_at=NOW() "
        "WHERE code=%s AND email=%s "
        "  AND consumed_at IS NULL AND expires_at > NOW() "
        "  AND failed_attempts < %s",
        (code, email, _MAX_CODE_ATTEMPTS))
    if cur.rowcount != 1:
        # No match — burn an attempt on EVERY currently-open link for
        # this email, so a brute-forcer can't get unlimited tries by
        # cycling through codes (the attempt cap applies across the
        # set of open links for the email, not per-code).
        cur.execute(
            "UPDATE magic_link SET failed_attempts = failed_attempts + 1 "
            "WHERE email=%s AND consumed_at IS NULL "
            "  AND expires_at > NOW()",
            (email,))
        get_db().commit()
        return None

    # Success path: NOW that the user has proven control of the email,
    # materialize their app_user row (or look it up if it exists from
    # a prior consume), backfill magic_link.user_id, stamp last_login.
    user = get_or_create_user(email)
    if not user:
        get_db().commit()
        return None
    cur.execute("UPDATE magic_link SET user_id=%s "
                "WHERE code=%s AND email=%s AND consumed_at IS NOT NULL "
                "ORDER BY id DESC LIMIT 1",
                (user["id"], code, email))
    cur.execute("UPDATE app_user SET last_login=NOW() WHERE id=%s",
                (user["id"],))
    get_db().commit()
    return user


def consume_magic_link(token: str) -> Optional[dict]:
    """Validate a token and (on success) log the user in by setting
    `session['user_id']`. Returns the user dict, or None if the link
    is invalid / expired / already consumed.

    On success: materializes the app_user row if it doesn't exist yet
    (deferred-creation per security finding L2) using the email stored
    on the magic_link row, then backfills magic_link.user_id.

    Atomic-ish: the UPDATE sets `consumed_at` and only succeeds when
    the row is still unconsumed and not expired — so a concurrent
    double-click of the link only mints ONE session, the second
    click fails."""
    if not token or len(token) < 8:
        return None
    cur = get_db().cursor()
    # Locate + consume in one UPDATE. rowcount==1 means we got it.
    cur.execute(
        "UPDATE magic_link SET consumed_at=NOW() "
        "WHERE token=%s AND consumed_at IS NULL "
        "  AND expires_at > NOW()",
        (token,))
    if cur.rowcount != 1:
        get_db().commit()
        return None
    # Read back the email from the consumed row to materialize the user.
    cur.execute(
        "SELECT email FROM magic_link WHERE token=%s", (token,))
    row = cur.fetchone()
    if not row or not row["email"]:
        get_db().commit()
        return None
    user = get_or_create_user(row["email"])
    if not user:
        get_db().commit()
        return None
    cur.execute("UPDATE magic_link SET user_id=%s WHERE token=%s",
                (user["id"], token))
    # Stamp last_login for visibility (helps debug "did this user
    # actually come back?" questions).
    cur.execute("UPDATE app_user SET last_login=NOW() WHERE id=%s",
                (user["id"],))
    get_db().commit()
    return user


# --------------------------------------------------------------------------- #
# session helpers
# --------------------------------------------------------------------------- #
def login(user: dict) -> None:
    """Establish a server-side session for `user`. Marks it permanent
    so Flask uses the configured PERMANENT_SESSION_LIFETIME (set in
    init below) rather than the default browser-session lifetime."""
    session["user_id"] = int(user["id"])
    session["user_email"] = user["email"]
    session.permanent = True


def logout() -> None:
    """Clear the auth-side session keys. Doesn't clear the rest of the
    session (drafts, etc.) — those are anonymous-friendly state."""
    session.pop("user_id", None)
    session.pop("user_email", None)


def current_user() -> Optional[dict]:
    """Return the logged-in user dict, or None. Cached on `g` so a
    single request only hits the DB once.

    Self-heals stale sessions: if `session['user_id']` is set but the
    referenced `app_user` row no longer exists (admin delete, GDPR
    purge, dev cleanup, restore from older backup), we clear the
    session keys and flash a one-shot warning so the next page tells
    the user what happened — rather than leaving them in a half-state
    where the cookie says "logged in" but the server treats them as
    anonymous, which silently breaks save flows."""
    from flask import g
    if hasattr(g, "_current_user"):
        return g._current_user
    uid = session.get("user_id")
    if not uid:
        g._current_user = None
        return None
    user = get_user_by_id(uid)
    if user is None:
        logger.warning(
            "Stale session.user_id=%s — user row missing, clearing", uid)
        # Mark that we just self-healed so /build/save and other
        # mutators can distinguish "this was a stale session, redirect
        # to login" from "this was always anonymous, proceed".
        session["_stale_session"] = True
        session.pop("user_id", None)
        session.pop("user_email", None)
        try:
            flash("You were signed out because your account record is "
                  "no longer available. Please sign in again.", "warning")
        except RuntimeError:
            # flash() requires an app context with session, which
            # current_user() always has when called from a view — but
            # be defensive in case it's called from a CLI/script path.
            pass
        g._current_user = None
        return None
    g._current_user = user
    return user


def init_app(app) -> None:
    """Set the permanent-session lifetime once per app init."""
    days = int(app.config.get("MAIL_SESSION_TTL_DAYS",
                               _SESSION_TTL_DAYS))
    app.permanent_session_lifetime = timedelta(days=days)
