from fastapi import FastAPI, responses
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware import Middleware  # 新增导入
from src.backend.app.api.endpoints import router
from src.backend.app.utils.logger import setup_logging
from src.backend.config import settings
from .services.switch_traffic_monitor import get_switch_monitor
from .services.traffic_monitor import traffic_monitor
from src.backend.app.api.database import init_db

def create_app() -> FastAPI:
    init_db()
    traffic_monitor.start_monitoring()
    setup_logging()

    app = FastAPI(
        title=settings.APP_NAME,
        debug=settings.DEBUG,
        docs_url=f"{settings.API_PREFIX}/docs",
        redoc_url=f"{settings.API_PREFIX}/redoc",
        openapi_url=f"{settings.API_PREFIX}/openapi.json",
        middleware=[
            Middleware(
                CORSMiddleware,
                allow_origins=["*"],
                allow_credentials=True,
                allow_methods=["*"],
                allow_headers=["*"],
            )
        ]
    )

    @app.get("/", include_in_schema=False)
    async def root():
        return responses.RedirectResponse(url=f"{settings.API_PREFIX}/docs")
    app.include_router(router, prefix=settings.API_PREFIX)
    return app

app = create_app()
