import logging
from fastapi import Request
from typing import Any, Optional, Dict
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware

from app.schemas import ResponseWrapper

log = logging.getLogger(__name__)
class HTTPException(Exception):

    def __init__(
        self,
        status_code: int,
        detail: Any = None,
        headers: Optional[Dict[str, Any]] = None,
    ) -> None:
        
        self.status_code = status_code
        self.detail = detail
        self.headers = headers

    def __repr__(self) -> str:
        """Class custom __repr__ method implementation.

        Returns:
            str: HTTPException string object.

        """
        kwargs = []

        for key, value in self.__dict__.items():
            if not key.startswith("_"):
                kwargs.append(f"{key}={value!r}")

        return f"{self.__class__.__name__}({', '.join(kwargs)})"


async def http_exception_handler(request: Request, exception: HTTPException) -> JSONResponse:

    return JSONResponse(
        status_code=exception.status_code,
        content=ResponseWrapper(
            status=False,
            message=exception.detail,
            data=None
        ).__dict__,
        headers=exception.headers,
    )

class GlobalExceptionMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        try:
            return await call_next(request)
        except Exception as exc:
            # Create a JSON response and add CORS headers manually
            log.exception(f"Error: {exc}", exc_info=True)
            return JSONResponse(
                status_code=500,
                content=ResponseWrapper(
                    status=False,
                    message="Internal server error",
                    data=None
                ).__dict__,
                headers={"Access-Control-Allow-Origin": "*"},
            )