# file: integrations/fastapi.py
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false

import random
import time
from collections.abc import Awaitable, Callable
from datetime import datetime, timezone

from fastapi import FastAPI  # type: ignore  # optional dep; see setup() annotation
from starlette.middleware.base import (  # type: ignore
    BaseHTTPMiddleware,
)
from starlette.requests import Request  # type: ignore
from starlette.responses import Response  # type: ignore

from ..apiTelemetry import (
    MAX_BODY_CAPTURE,
    TelemetryClient,
    capture_exception,
    extract_trace_id,
    sanitize_payload,
    spans_var,
    start_trace,
    trace_id_var,
)


class TelemetryMiddleware(BaseHTTPMiddleware):
    """
    FastAPI middleware to automatically instrument incoming HTTP requests.

    Captures request/response data, measures duration, handles exceptions,
    and submits the resulting trace to the telemetry client. Request and
    response BODIES are only read when capture is explicitly enabled
    (TELEMETRY_CAPTURE_BODIES); by default streaming responses (SSE, file
    downloads) pass through untouched.
    """

    def __init__(self, app, client: TelemetryClient):
        super().__init__(app)
        self.client = client

    async def dispatch(
        self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
    ) -> Response:
        method = request.method.upper()

        # Priority sample rate for critical methods (POST, PUT, PATCH, DELETE);
        # general rate for everything else.
        if method in ["POST", "PUT", "PATCH", "DELETE"]:
            sample_rate = self.client.config.priority_sample_rate
        else:
            sample_rate = self.client.config.general_sample_rate

        # 1. Sampling decision
        is_sampled = random.random() < sample_rate

        # 2. Errors are ALWAYS reported, even on unsampled requests.
        if not is_sampled:
            try:
                return await call_next(request)
            except Exception as e:
                capture_exception(e, self._error_context(request))
                raise

        # 3. Initialize trace context: adopt an incoming trace id when the
        # caller propagated one (distributed traces stay continuous across
        # services); otherwise start a brand-new trace.
        incoming_trace_id = extract_trace_id(request.headers)
        if incoming_trace_id is not None:
            trace_id_var.set(incoming_trace_id)
            trace_id = incoming_trace_id
        else:
            trace_id = start_trace()
        spans_var.set([])
        start_time = time.perf_counter()

        capture_bodies = self.client.config.capture_bodies
        req_body_bytes = b""
        if capture_bodies:
            req_body_bytes = (await request.body())[:MAX_BODY_CAPTURE]

        response = None
        has_error = False
        status_code = 500  # Default in case of unhandled exception

        try:
            # 4. Process the request
            response = await call_next(request)
            status_code = response.status_code
        except Exception as e:
            has_error = True
            capture_exception(e, self._error_context(request))
            # Re-raise the exception to let FastAPI handle it
            raise
        finally:
            # 5. Finalize and send the trace
            if spans_var.get() is not None:  # Ensure context is still valid
                duration_ms = (time.perf_counter() - start_time) * 1000
                collected_spans = spans_var.get() or []

                res_body_bytes = b""
                if response and capture_bodies:
                    # Only materialize the response when explicitly enabled;
                    # with capture disabled the stream passes through untouched.
                    res_body_iterator = response.body_iterator
                    async for chunk in res_body_iterator:
                        res_body_bytes += chunk
                    response.body_iterator = self.recreate_iterator(res_body_bytes)
                    res_body_bytes = res_body_bytes[:MAX_BODY_CAPTURE]

                req_body_str = req_body_bytes.decode("utf-8", errors="replace")
                res_body_str = res_body_bytes.decode("utf-8", errors="replace")

                end_dt = datetime.now(timezone.utc)
                start_dt = datetime.fromtimestamp(
                    end_dt.timestamp() - (duration_ms / 1000), tz=timezone.utc
                )

                # Never let a malformed duration crash the request path.
                try:
                    duration_ms_int = int(duration_ms)
                except (TypeError, ValueError):
                    duration_ms_int = 0

                trace_payload = {
                    "trace": {
                        "id": trace_id,
                        "http_method": request.method,
                        "http_path": request.url.path,
                        "http_host": request.url.hostname,
                        "http_status_code": status_code,
                        "request_body": sanitize_payload(req_body_str),
                        "response_body": sanitize_payload(res_body_str),
                        "duration_ms": duration_ms_int,
                        "has_error": has_error or status_code >= 500,
                        "start_timestamp": start_dt.isoformat(),
                        "end_timestamp": end_dt.isoformat(),
                    },
                    "logs_and_spans": collected_spans,
                }
                self.client.capture_trace(trace_payload)

            # 6. Clean up context variables
            spans_var.set(None)
            trace_id_var.set(None)

        return response

    @staticmethod
    def _error_context(request: Request) -> dict:
        client_host = request.client.host if request.client is not None else None
        return {
            "method": request.method,
            "path": request.url.path,
            "client": client_host,
        }

    async def recreate_iterator(self, content: bytes):
        """Helper to recreate a byte iterator for the response."""
        yield content


def setup(app: FastAPI, client: TelemetryClient):
    """
    Applies the TelemetryMiddleware to the FastAPI application.

    Args:
        app (FastAPI): The FastAPI application instance.
        client (TelemetryClient): The active telemetry client instance.
    """
    app.add_middleware(TelemetryMiddleware, client=client)
