from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import asyncio

from app.application.token_middleware import TokenMiddleware
from app.application.logger_middleware import LoggerMiddleware
from app.api.common.upload_file import upload_files
from app.api.sys.login_api import login
from app.api.sys.sys_user_api import user
from app.api.business.project_train_api import project
from app.api.common.view_img import view
from app.api.business.project_detect_api import detect
from app.api.business.websocket_api import web_socket
from app.util.ps_util import get_server_json
from app.websocket.web_socket_server import room_manager

my_app = FastAPI()


'''
添加CROS中间件，允许跨域请求
'''
my_app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

'''
注意中间的顺序，这个地方是倒序执行的
'''
my_app.add_middleware(LoggerMiddleware)
my_app.add_middleware(TokenMiddleware)

my_app.include_router(view, tags=["查看图片"])
my_app.include_router(login, prefix="/login", tags=["用户登录接口"])
my_app.include_router(upload_files, prefix="/upload", tags=["文件上传API"])
my_app.include_router(user, prefix="/user", tags=["用户管理API"])
my_app.include_router(project, prefix="/proj", tags=["项目训练API"])
my_app.include_router(detect, prefix="/detect", tags=["项目推理API"])
my_app.include_router(web_socket, prefix="/ws", tags=["websocket管理"])


# fastapi定时执行任务
async def serve_info_task():
    while True:
        server_json = get_server_json()
        await room_manager.send_to_room('server-info', server_json)
        await asyncio.sleep(5)  # 每 5 秒执行


@my_app.on_event("startup")
async def start_periodic_task():
    # 在后台启动异步任务
    asyncio.create_task(serve_info_task())



