from aws_lambda_powertools.utilities import parameters
from fastapi import FastAPI, Response, status
from fastapi.middleware.cors import CORSMiddleware
from mangum import Mangum
from snapshot_restore_py import register_before_snapshot
from src.routers.client import api_keys_router, client_tenants_router, quota_router, usage_events_router
from src.routers.client.descriptions import ROOT_DESCRIPTION
from src.settings import Settings
from src.tracer import tracer

settings = Settings()


@register_before_snapshot
def get_db_secret() -> None:
    if settings.postgres_secret_name:
        one_year = 31104000
        # snapshot内にキャッシュを作成する
        parameters.get_secret(settings.postgres_secret_name, max_age=one_year)  # 一月に一度はデプロイされる想定


app = FastAPI(
    title="AI Unit クライアント API",
    description=ROOT_DESCRIPTION,
    version="1.0.0",
    docs_url=None,  # セキュリティのため、利用しないドキュメントは非表示
    # RedocのAPIドキュメントでは、openapi_tagsで指定した順序でエンドポイントが表示される
    openapi_tags=[
        {"name": "クォータ"},
        {"name": "使用イベント"},
        {"name": "テナント"},
        {"name": "APIキー"},
        {"name": "その他"},
    ],
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get(
    "/",
    summary="ヘルスチェック",
    tags=["その他"],
    status_code=status.HTTP_200_OK,
    responses={
        status.HTTP_200_OK: {
            "description": "正常に起動",
        },
        status.HTTP_500_INTERNAL_SERVER_ERROR: {
            "description": "内部エラー",
        },
    },
)
async def health_check() -> Response:
    return Response(
        content="AI Unit Client API is running.",
        status_code=status.HTTP_200_OK,
    )


API_BASE_RESOURCE = "/v1"
app.include_router(
    usage_events_router.router,
    prefix=API_BASE_RESOURCE,
)
app.include_router(
    quota_router.router,
    prefix=API_BASE_RESOURCE,
)
app.include_router(
    client_tenants_router.router,
    prefix=API_BASE_RESOURCE,
)
app.include_router(
    api_keys_router.router,
    prefix=API_BASE_RESOURCE,
)

mangum = Mangum(app)


@tracer.capture_lambda_handler
def handler(event, context):
    return mangum(event, context)
