# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
FastAPI 应用实例（可扩展）

用法:
    # 方式 1: 直接使用（内置路由）
    from infoman.service.app import application

    # 方式 2: 扩展应用（添加自己的路由）
    from infoman.service.app import application
    from fastapi import APIRouter

    router = APIRouter()

    @router.get("/my-endpoint")
    def my_endpoint():
        return {"message": "My custom endpoint"}

    application.include_router(router, prefix="/api", tags=["custom"])

    # 方式 3: 启动应用
    # infoman-serve  # 使用内置应用
"""

from infoman.config.settings import settings
from infoman.logger import setup_logger
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from infoman.service.middleware.logging import LoggingMiddleware
from infoman.service.middleware.request_id import RequestIDMiddleware
from infoman.service.routers import api_router
from infoman.config.settings import settings as config
from infoman.service.core.response import ProRJSONResponse
from infoman.service.core.monitor import instrumentator
from infoman.service.core.lifespan import lifespan
from infoman.service.exception.handler import register_exception_handlers

# ============ 日志配置 ============
setup_logger(config=settings)

# ============ 创建 FastAPI 应用实例 ============
application = FastAPI(
    title=config.APP_NAME,
    docs_url=config.DOCS_URL,
    redoc_url=config.APP_REDOC_URL,
    description=config.APP_DESCRIPTION,
    default_response_class=ProRJSONResponse,
    lifespan=lifespan
)

# ============ 异常处理器 ============
register_exception_handlers(application)

# ============ 中间件（添加顺序和执行顺序相反-洋葱模型） ============
application.add_middleware(GZipMiddleware, minimum_size=1000)
application.add_middleware(
    CORSMiddleware,
    allow_origins=config.ALLOW_ORIGINS,
    allow_credentials=config.ALLOW_CREDENTIALS,
    allow_methods=config.ALLOW_METHODS,
    allow_headers=config.ALLOW_HEADERS,
    max_age=600,
)
application.add_middleware(RequestIDMiddleware)
application.add_middleware(LoggingMiddleware)

# ============ 内置路由（可选，用户可以选择不使用） ============
application.include_router(api_router)

# ============ Prometheus 监控 ============
instrumentator.instrument(application).expose(application, endpoint="/metrics")
