"""Internal endpoint Better Auth posts to for verification / reset / invitation emails.

Not for public consumption. Authenticated via HMAC-SHA256(body, INTERNAL_EMAIL_SHARED_SECRET).
"""

import hashlib
import hmac
from typing import Annotated, Literal

import logfire
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
from pydantic import BaseModel, EmailStr, ValidationError

from app.config import Settings, get_settings
from app.email.auth_emails import SUPPORTED_KINDS, dispatch_auth_email
from app.email.scaleway import ScalewayEmailClient

router = APIRouter(prefix="/internal/auth", tags=["internal-auth"], include_in_schema=False)


class _AuthEmailPayload(BaseModel):
    kind: Literal[
        "verify-email",
        "verify-email-reminder",
        "reset-password",
        "invitation",
        "invitation-reminder",
    ]
    to: EmailStr
    name: str | None = None
    url: str | None = None
    organizationName: str | None = None
    inviterEmail: str | None = None


def _verify_signature(body: bytes, signature: str, secret: str) -> bool:
    if not secret or not signature:
        return False
    expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


def _assert_secret_configured() -> None:
    """Fail loud in production if the HMAC secret is missing.

    Without this guard, `_verify_signature` would silently return False for
    every request, so BA would correctly get a 401 — but every auth email
    would be silently dropping in the wild with no visible cause beyond a
    log line.
    """
    settings = get_settings()
    if settings.ENVIRONMENT == "production" and not settings.INTERNAL_EMAIL_SHARED_SECRET:
        raise RuntimeError(
            "INTERNAL_EMAIL_SHARED_SECRET must be set in production. "
            "Without it, every Better Auth email (verification, reset, "
            "invitation) is silently rejected at /internal/auth/email."
        )


_assert_secret_configured()


@router.post("/email", status_code=status.HTTP_202_ACCEPTED)
async def send_auth_email(
    request: Request,
    x_internal_auth: Annotated[str | None, Header(alias="X-Internal-Auth")] = None,
    settings: Settings = Depends(get_settings),
) -> dict[str, str]:
    body = await request.body()
    if not _verify_signature(body, x_internal_auth or "", settings.INTERNAL_EMAIL_SHARED_SECRET):
        raise HTTPException(status_code=401, detail="Invalid HMAC signature")

    try:
        payload = _AuthEmailPayload.model_validate_json(body)
    except ValidationError as exc:
        raise HTTPException(status_code=400, detail=f"Invalid payload: {exc}") from exc

    if payload.kind not in SUPPORTED_KINDS:
        raise HTTPException(status_code=400, detail=f"Unknown kind: {payload.kind}")

    client = ScalewayEmailClient()
    try:
        await dispatch_auth_email(
            client,
            kind=payload.kind,
            to=str(payload.to),
            name=payload.name,
            url=payload.url,
            organization_name=payload.organizationName,
            inviter_email=payload.inviterEmail,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except Exception as exc:
        logfire.error("internal_auth_email_dispatch_failed", kind=payload.kind, error=str(exc))
        raise HTTPException(status_code=502, detail="Email dispatch failed") from exc

    logfire.info("internal_auth_email_sent", kind=payload.kind, to=str(payload.to))
    return {"status": "accepted"}
