import os
from typing import Any

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler.api_gateway import (
    APIGatewayHttpResolver,
    Response,
    content_types,
)
from aws_lambda_powertools.event_handler.exceptions import ServiceError
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext

from middlewares import AuthorizerMiddleware
from routes import courses, enrollments, lookup, me, orders, users, webhooks

DEBUG = os.getenv('LOG_LEVEL') == 'DEBUG'

tracer = Tracer()
logger = Logger(__name__)
app = APIGatewayHttpResolver(enable_validation=True, debug=DEBUG)
app.use(middlewares=[AuthorizerMiddleware()])
app.include_router(courses.router, prefix='/courses')
app.include_router(enrollments.router, prefix='/enrollments')
app.include_router(orders.router, prefix='/orders')
app.include_router(users.router, prefix='/users')
app.include_router(webhooks.router, prefix='/webhooks')
app.include_router(me.router, prefix='/me')
app.include_router(lookup.router, prefix='/lookup')


@app.exception_handler(ServiceError)
def exc_error(exc: ServiceError):
    return Response(
        body={
            'msg': exc.msg,
            'err': type(exc).__name__,
        },
        content_type=content_types.APPLICATION_JSON,
        status_code=exc.status_code,
    )


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_HTTP)
@tracer.capture_lambda_handler
def lambda_handler(event: dict[str, Any], context: LambdaContext) -> dict[str, Any]:
    return app.resolve(event, context)
