import uuid

from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send

from app.core.config import settings
from app.core.logging import reset_request_id, set_request_id

# Standard response headers with no downside for a pure JSON API. No
# Content-Security-Policy here on purpose — /docs and /redoc render
# Swagger/ReDoc's own HTML+inline-script UI, and a CSP strict enough to
# matter would need to special-case those two routes; not worth the
# complexity until this API actually serves browser-rendered content
# beyond the docs.
_SECURITY_HEADERS = {
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    # Ignored by browsers over plain HTTP, so this is safe to always
    # send rather than conditioning it on the scheme — a deployment
    # behind TLS just gets the benefit for free.
    "Strict-Transport-Security": "max-age=63072000; includeSubDomains",
}
_SECURITY_HEADERS_ENCODED = [
    (k.lower().encode("latin-1"), v.encode("latin-1"))
    for k, v in _SECURITY_HEADERS.items()
]


class SecurityHeadersMiddleware:
    """Deliberately plain ASGI middleware, not Starlette's
    BaseHTTPMiddleware — BaseHTTPMiddleware runs call_next() inside an
    anyio task group, which re-wraps any exception raised by the app
    (or a downstream middleware) into an ExceptionGroup and breaks
    app.main's global exception handler's ability to catch it. Working
    at the raw ASGI send() level avoids that entirely."""

    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        async def send_wrapper(message: Message) -> None:
            if message["type"] == "http.response.start":
                headers = list(message.get("headers", []))
                existing = {name for name, _value in headers}
                for name, value in _SECURITY_HEADERS_ENCODED:
                    if name not in existing:
                        headers.append((name, value))
                message = {**message, "headers": headers}
            await send(message)

        await self.app(scope, receive, send_wrapper)


_REQUEST_ID_HEADER = b"x-request-id"


class RequestIdMiddleware:
    """Assigns every request (and websocket connection) an ID — reused
    from an incoming X-Request-ID header if the deployment sits behind
    a proxy/load balancer that already sets one, otherwise a fresh
    uuid4 — and makes it available to app.core.logging's filter for
    the lifetime of the request via a contextvar. Echoed back as a
    response header so a client (or the proxy in front of this
    service) can correlate its own logs with ours for the same
    request. Runs first in the middleware stack (added last, since
    Starlette applies middleware in reverse-registration order) so
    every other middleware's and the app's own logging already has it
    set."""

    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] not in ("http", "websocket"):
            await self.app(scope, receive, send)
            return

        headers = dict(scope.get("headers") or [])
        incoming = headers.get(_REQUEST_ID_HEADER)
        request_id = incoming.decode("latin-1") if incoming else uuid.uuid4().hex
        token = set_request_id(request_id)
        # Also stashed on scope state, not just the contextvar: Starlette
        # runs the @app.exception_handler(Exception) catch-all inside
        # ServerErrorMiddleware, which wraps *outside* every middleware
        # added via app.add_middleware() including this one — by the
        # time that handler runs, the finally block below has already
        # reset the contextvar. scope["state"] isn't touched by that
        # reset, so it's what app.main's handler reads from instead.
        scope.setdefault("state", {})["request_id"] = request_id

        async def send_wrapper(message: Message) -> None:
            if message["type"] in ("http.response.start", "websocket.accept"):
                headers = list(message.get("headers", []))
                headers.append((_REQUEST_ID_HEADER, request_id.encode("latin-1")))
                message = {**message, "headers": headers}
            await send(message)

        try:
            await self.app(scope, receive, send_wrapper)
        finally:
            reset_request_id(token)


class RequestBodySizeLimitMiddleware:
    """Rejects a request before the app ever sees it if its declared
    Content-Length exceeds settings.max_request_body_bytes (read fresh
    on every request, not captured once at app startup, so tests can
    monkeypatch it). Deliberately checks only the header, not actual
    bytes received as they stream in — enforcing a hard cap on an
    unbounded chunked-transfer body (no Content-Length at all) would
    need buffering/counting logic this middleware doesn't do. Still
    closes the common case: a client (malicious or just careless)
    declaring an oversized body up front is rejected before a single
    byte of it is read into memory, rather than only failing deep
    inside whatever endpoint happens to try to parse it."""

    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        headers = dict(scope.get("headers") or [])
        content_length = headers.get(b"content-length")
        if content_length is not None:
            try:
                declared_bytes = int(content_length)
            except ValueError:
                declared_bytes = None
            if (
                declared_bytes is not None
                and declared_bytes > settings.max_request_body_bytes
            ):
                response = JSONResponse(
                    status_code=413, content={"detail": "Request body too large."}
                )
                await response(scope, receive, send)
                return

        await self.app(scope, receive, send)
