"""
==================================================
Smart Attendance AI
Global Exception Handlers
==================================================
"""

import time

from fastapi import Request
from fastapi.responses import JSONResponse

from config.logger import logger

from utils.error_codes import ERROR_CODES
from utils.response import error_response
from utils.exceptions import AIException


# ==================================================
# AI Exception Handler
# ==================================================

async def ai_exception_handler(
    request: Request,
    exc: AIException
):

    # ==========================================
    # Request Information
    # ==========================================

    request_id = getattr(
        request.state,
        "request_id",
        "unknown"
    )

    start_time = getattr(
        request.state,
        "start_time",
        None
    )

    processing_time = None

    if start_time is not None:

        processing_time = round(

            (
                time.perf_counter()
                - start_time
            ) * 1000,

            2

        )

    # ==========================================
    # Error Code
    # ==========================================

    code = ERROR_CODES.get(

        exc.__class__.__name__,

        "UNKNOWN_ERROR"

    )

    # ==========================================
    # Logging
    # ==========================================

    logger.warning(

        "[%s] %s",

        request_id,

        str(exc)

    )

    # ==========================================
    # Response
    # ==========================================

    return JSONResponse(

        status_code=400,

        content=error_response(

            message=str(exc),

            errors=[

                {

                    "code": code,

                    "detail": str(exc)

                }

            ],

            meta={

                "request_id": request_id,

                "processing_time_ms": processing_time

            }

        )

    )


# ==================================================
# General Exception Handler
# ==================================================

async def general_exception_handler(
    request: Request,
    exc: Exception
):

    # ==========================================
    # Request Information
    # ==========================================

    request_id = getattr(

        request.state,

        "request_id",

        "unknown"

    )

    start_time = getattr(

        request.state,

        "start_time",

        None

    )

    processing_time = None

    if start_time is not None:

        processing_time = round(

            (
                time.perf_counter()
                - start_time
            ) * 1000,

            2

        )

    # ==========================================
    # Logging
    # ==========================================

    logger.exception(

        "[%s] %s",

        request_id,

        str(exc)

    )

    # ==========================================
    # Response
    # ==========================================

    return JSONResponse(

        status_code=500,

        content=error_response(

            message="Internal Server Error",

            errors=[

                {

                    "code": ERROR_CODES.get(

                        "Exception",

                        "INTERNAL_SERVER_ERROR"

                    ),

                    "detail": str(exc)

                }

            ],

            meta={

                "request_id": request_id,

                "processing_time_ms": processing_time

            }

        )

    )