"""
Error handling middleware
"""
from fastapi import Request, status
from fastapi.responses import JSONResponse
import grpc
import structlog
from utils.error_translation import grpc_error_to_http
from config import settings

logger = structlog.get_logger()

async def error_handler_middleware(request: Request, call_next):
    """
    Middleware to catch and handle errors consistently
    """
    try:
        response = await call_next(request)
        return response
    except grpc.RpcError as e:
        # Handle gRPC errors from SDK Bridge
        logger.error("grpc_error",
                    method=request.method,
                    path=request.url.path,
                    grpc_code=e.code(),
                    details=e.details())

        http_status, error_body = grpc_error_to_http(e)

        return JSONResponse(
            status_code=http_status,
            content=error_body
        )
    except Exception as e:
        # Handle unexpected errors
        logger.error("unexpected_error",
                    method=request.method,
                    path=request.url.path,
                    error=str(e),
                    exc_info=True)

        # Don't expose internal details in production
        if settings.ENVIRONMENT == "production":
            message = "An unexpected error occurred"
        else:
            message = str(e)

        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={
                "error": "InternalError",
                "message": message
            }
        )
