"""Analytics collection middleware.

Tracks API requests for analytics when enabled.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
"""

from __future__ import annotations

import logging
import time
from typing import Callable

from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware

logger = logging.getLogger("{{ project_name }}.analytics.middleware")

EXCLUDE_PATHS: set[str] = {{ '{' }}{{ exclude_paths | map('tojson') | join(', ') }}{{ '}' }}


class AnalyticsMiddleware(BaseHTTPMiddleware):
    """Middleware that records analytics for API requests."""

    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        path = request.url.path

        # Skip excluded paths
        if path in EXCLUDE_PATHS or any(path.startswith(p) for p in EXCLUDE_PATHS):
            return await call_next(request)

        start_time = time.monotonic()
        response = await call_next(request)
        duration_ms = (time.monotonic() - start_time) * 1000

        # Record asynchronously to avoid blocking the response
        try:
            from {{ project_name }}.analytics.service import record_event

            properties = {
                "method": request.method,
                "path": path,
                "status_code": response.status_code,
                "duration_ms": round(duration_ms, 2),
{% if track_device_info %}
                "user_agent": request.headers.get("user-agent", ""),
{% endif %}
{% if track_referrer %}
                "referrer": request.headers.get("referer", ""),
{% endif %}
            }

{% if auth_enabled %}
            # Include user info if authenticated
            user = getattr(request.state, "user", None)
            if user:
{% if anonymize_users %}
                import hashlib

                user_id = hashlib.sha256(str(user.id).encode()).hexdigest()[:16]
{% else %}
                user_id = str(user.id)
{% endif %}
                properties["user_id"] = user_id
{% endif %}

            await record_event(
                event_name="api_call",
                category="api",
                properties=properties,
            )
        except Exception:
            logger.debug("Failed to record analytics for %s %s", request.method, path)

        return response
