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

"""
# Time       ：2025/6/21 20:02
# Author     ：Maxwell
# Description：
"""
import platform

if platform.system() != "Windows":
    import uvloop

    uvloop.install()
    print("uvloop installed")
else:
    print("Running on Windows, uvloop not available")

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.config 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

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_ORIGIN,
    allow_credentials=config.ALLOW_CREDIENTIALS,
    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, include_in_schema=False)


# ===== 应用到 FastAPI =====
instrumentator.instrument(application).expose(application, endpoint="/metrics")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(application, host=config.APP_HOST, port=int(config.APP_PORT))
