import json
import os
from functools import partial
from typing import Any

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler.api_gateway import (
    APIGatewayHttpResolver,
    CORSConfig,
)
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 api_gateway import JSONResponse
from json_encoder import JSONEncoder
from routes import courses, enrollments, orders, orgs, users

logger = Logger(__name__)
tracer = Tracer()
debug = 'AWS_SAM_LOCAL' in os.environ
serializer = partial(json.dumps, separators=(',', ':'), cls=JSONEncoder)
cors = CORSConfig(
    allow_origin='*',
    allow_headers=['Content-Type', 'X-Requested-With', 'Authorization'],
    max_age=600,
    allow_credentials=False,
)
app = APIGatewayHttpResolver(
    enable_validation=True,
    cors=cors,
    debug=debug,
    serializer=serializer,
)
app.enable_swagger(path='/swagger')
app.include_router(courses.router, prefix='/courses')
app.include_router(enrollments.router, prefix='/enrollments')
app.include_router(enrollments.cancel, prefix='/enrollments')
app.include_router(enrollments.dedup_window, prefix='/enrollments')
app.include_router(enrollments.download_cert, prefix='/enrollments')
app.include_router(enrollments.enroll, prefix='/enrollments')
app.include_router(enrollments.scorm, prefix='/enrollments')
app.include_router(users.router, prefix='/users')
app.include_router(users.emails, prefix='/users')
app.include_router(users.orgs, prefix='/users')
app.include_router(users.password, prefix='/users')
app.include_router(orders.router, prefix='/orders')
app.include_router(orgs.admins, prefix='/orgs')
app.include_router(orgs.custom_pricing, prefix='/orgs')
app.include_router(orgs.scheduled, prefix='/orgs')
app.include_router(orgs.users, prefix='/orgs')


@app.get('/health')
def health():
    return {'status': 'available'}


@app.exception_handler(ServiceError)
def exc_error(exc: ServiceError):
    return JSONResponse(
        body={
            'type': type(exc).__name__,
            'message': str(exc),
        },
        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)
