import logging

import sentry_sdk
from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from app.api.v1.endpoints.tracking import ws_router as tracking_ws_router
from app.api.v1.router import api_router
from app.core.config import settings
from app.core.logging import configure_logging, set_request_id
from app.core.middleware import (
    RequestBodySizeLimitMiddleware,
    RequestIdMiddleware,
    SecurityHeadersMiddleware,
)
from app.services.rate_limit import rate_limit_global

configure_logging()
logger = logging.getLogger("yeneb.errors")

# Empty by default (local dev/tests), same opt-in-when-configured
# pattern as the other providers in app.core.config — only reports
# errors once a real DSN is set. send_default_pii=False: this API
# handles phone numbers, PINs, and payment details, none of which
# should ever leave the process in an error report.
if settings.sentry_dsn:
    sentry_sdk.init(
        dsn=settings.sentry_dsn,
        environment=settings.environment,
        traces_sample_rate=settings.sentry_traces_sample_rate,
        send_default_pii=False,
    )

# Descriptions shown grouped by tag in /docs and /redoc, and in the
# exported openapi.json (see app.commands.export_openapi) — order here
# is also the display order in the docs UI. Tag names must match each
# router's own `tags=[...]` exactly (see app/api/v1/endpoints/*.py).
_OPENAPI_TAGS = [
    {
        "name": "health",
        "description": "Liveness/readiness checks — no auth, not rate-limited.",
    },
    {
        "name": "auth",
        "description": "Signup, login, Google Sign-In, PIN reset/change, invited-account activation, add-phone/add-email.",
    },
    {
        "name": "admin",
        "description": "Admin-console operations: invites, courier management, user roster, analytics.",
    },
    {"name": "uploads", "description": "Image upload (courier/merchant photos, etc.)."},
    {
        "name": "merchants",
        "description": "Merchant (business/brand) CRUD and discovery.",
    },
    {
        "name": "branches",
        "description": "Branch browse/search, settings, and full menu management.",
    },
    {"name": "cart", "description": "The logged-in customer's single shopping cart."},
    {
        "name": "group-orders",
        "description": "In-person group ordering — a shared cart via join code, each participant paying independently for their own items.",
    },
    {
        "name": "orders",
        "description": "Checkout, order lifecycle, cancellation, reorder, reviews.",
    },
    {
        "name": "webhooks",
        "description": "Third-party payment-gateway callbacks (Chapa) — not called by the app directly.",
    },
    {"name": "promo-codes", "description": "Promo code CRUD."},
    {
        "name": "reviews",
        "description": "Editing, staff replies, and admin moderation for reviews.",
    },
    {
        "name": "courier",
        "description": "Courier-side delivery workflow: offers, pickup/delivery, earnings.",
    },
    {
        "name": "tracking",
        "description": "Live order tracking: REST snapshot, WebSocket ticket mint, and the WebSocket feed itself.",
    },
    {
        "name": "customer",
        "description": "Customer-only self-service: favorites, optional profile.",
    },
    {
        "name": "notifications",
        "description": "Push-notification device token registration.",
    },
]

app = FastAPI(
    title=settings.app_name,
    version="1.0.0",
    description=(
        "Yeneb CODS backend API. All routes are under `/api/v1`. Bearer-"
        "token auth (JWT access token in the `Authorization` header) "
        "unless noted otherwise. See `docs/API_ERRORS.md` in the repo "
        "for a full per-domain error-code reference, including the "
        "cross-cutting rate-limit and auth-failure behavior that "
        "applies across nearly every route."
    ),
    openapi_tags=_OPENAPI_TAGS,
)

app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RequestBodySizeLimitMiddleware)
# allow_credentials=False: this API is Bearer-token-only, never
# cookie-based, so there's no session to carry cross-origin and no
# reason to widen the browser's CORS credential exposure.
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_allowed_origins,
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)
# Added last so it runs first (Starlette applies middleware in
# reverse-registration order) — every other middleware and the app
# itself should already see the request ID in place.
app.add_middleware(RequestIdMiddleware)

# rate_limit_global is a broad per-IP backstop on top of (not instead
# of) the tighter, action-specific limits already on individual auth
# endpoints — see app.services.rate_limit.
app.include_router(
    api_router, prefix="/api/v1", dependencies=[Depends(rate_limit_global)]
)
# Mounted separately, without rate_limit_global: that dependency is
# typed to take a `Request`, which doesn't exist on a websocket ASGI
# scope — see app.api.v1.endpoints.tracking for the full reasoning.
app.include_router(tracking_ws_router, prefix="/api/v1")


@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """Last-resort safety net for anything that isn't an HTTPException
    (every intentional error response in this codebase already is one,
    and FastAPI's own handler for those takes precedence over this —
    this only ever fires for a genuine bug). Logs the real exception
    server-side; the client only ever sees a generic message, never a
    stack trace or internal detail.

    Registering this handler makes FastAPI convert the exception into
    a JSONResponse before it ever propagates out of the ASGI app, which
    would otherwise stop Sentry's automatic capture from seeing it —
    so this reports it explicitly. A no-op when sentry_dsn isn't set
    (capture_exception is safe to call with no client configured).

    Starlette runs this handler from inside ServerErrorMiddleware,
    which wraps *outside* every middleware added via
    app.add_middleware() — including RequestIdMiddleware, whose finally
    block has already reset its contextvar by the time we get here, and
    whose response-header injection never sees this handler's response
    at all. request.state.request_id (set on the scope, not the
    contextvar, by RequestIdMiddleware) survives that unwind, so it's
    what this reads; the contextvar is then explicitly re-set from it
    purely so this function's own logger.exception call — which does
    go through the normal request_id-in-every-log-line filter — reports
    the right value too."""
    request_id = getattr(request.state, "request_id", "-")
    set_request_id(request_id)
    sentry_sdk.set_tag("request_id", request_id)
    sentry_sdk.capture_exception(exc)
    logger.exception("Unhandled error on %s %s", request.method, request.url.path)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error.", "request_id": request_id},
        headers={"X-Request-ID": request_id},
    )


@app.get("/")
def root():
    return {"message": f"{settings.app_name} is running"}
