"""Custom exceptions for the application."""

from fastapi import HTTPException, status


class AppException(Exception):
    """Base application exception."""

    status_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR
    code: str = "internal_error"

    def __init__(self, message: str = None):
        self.message = message or "An internal error occurred"
        super().__init__(self.message)


class NotFoundException(AppException):
    """Resource not found exception."""

    status_code = status.HTTP_404_NOT_FOUND
    code = "not_found"

    def __init__(self, resource: str = "Resource"):
        super().__init__(f"{resource} not found")


class ValidationException(AppException):
    """Validation error exception."""

    status_code = status.HTTP_400_BAD_REQUEST
    code = "validation_error"


class ConflictException(AppException):
    """Conflict error exception."""

    status_code = status.HTTP_409_CONFLICT
    code = "conflict"


class ScenarioNotRunningException(AppException):
    """Scenario is not in running state."""

    status_code = status.HTTP_400_BAD_REQUEST
    code = "scenario_not_running"

    def __init__(self):
        super().__init__("Scenario is not in 'running' state. Cannot ingest logs.")


def setup_exception_handlers(app):
    """Setup exception handlers for FastAPI app."""
    from fastapi import Request
    from fastapi.responses import JSONResponse

    @app.exception_handler(AppException)
    async def app_exception_handler(request: Request, exc: AppException):
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "error": exc.code,
                "message": exc.message,
                "status_code": exc.status_code,
            },
        )
