"""Middleware to log per-request usage by email."""

from typing import Callable
import time
from starlette.requests import Request
from starlette.responses import Response

from agenticlypay.utils.firestore_storage import FirestoreStorage

storage = FirestoreStorage()


async def usage_middleware(request: Request, call_next: Callable[[Request], Response]) -> Response:
    """Log API usage to Firestore by email."""
    # Skip logging for OPTIONS requests (CORS preflight) and health checks
    if request.method == "OPTIONS" or request.url.path in ["/", "/health", "/api/v1/console/ping"]:
        return await call_next(request)
    
    response: Response = await call_next(request)

    # Extract email from headers only (fast path) and log synchronously
    email = request.headers.get("X-Developer-Email") or request.query_params.get("email")
    
    # Log usage if we have an email (fire and forget, don't block)
    if email and response.status_code < 500:
        try:
            endpoint = f"{request.method} {request.url.path}"
            storage.log_usage(email=email, endpoint=endpoint, status_code=response.status_code)
        except Exception:
            pass  # Don't let logging failures affect responses

    return response
