import asyncio
import sys
import uvicorn
import signal
from api import *
from sockets.socket_server import *
import uvicorn.loops.auto
import uvicorn.protocols.http.auto
import uvicorn.protocols.websockets.auto
import uvicorn.lifespan.on
from multiprocessing import Process, freeze_support
from service.init_load_source import init_load_source
import socket

def handle_shutdown(signum, frame):
    """关闭系统应用服务"""
    # 终止事件循环
    loop = asyncio.get_event_loop()
    # 适当地关闭服务器
    for task in asyncio.all_tasks(loop):
        print("清除:", task.get_name())
        task.cancel()
    loop.call_soon_threadsafe(loop.stop)
    sys.exit(0)


async def run_server():
    # 启动uvicorn服务器
    isDebug = True if IS_DEBUG == "true" else False
    config = uvicorn.Config(
        APP_RUN,
        host=APP_HOST,
        port=int(PORT),
        workers=int(APP_WORKS),
        loop="asyncio",
        ws_ping_interval=20,  # 每 20 秒发一次 WebSocket Ping 帧
        ws_ping_timeout=10,  # 等待 Pong 最多 10 秒
    )
    # 创建自定义 socket
    server = uvicorn.Server(config)
    try:
        await server.serve()
    except asyncio.CancelledError:
        # 正确处理取消操作
        pass
    finally:
        # 确保服务器正确关闭
        if hasattr(server, "shutdown"):
            await server.shutdown()


async def main():
    # 创建可取消的任务
    server_task = asyncio.create_task(run_server())
    load_task = asyncio.create_task(init_load_source().load_source())

    try:
        await asyncio.gather(server_task, load_task)
    except asyncio.CancelledError:
        # 取消所有任务
        for task in [server_task, load_task]:
            if not task.done():
                task.cancel()
        # 等待任务完成取消
        await asyncio.gather(server_task, load_task, return_exceptions=True)


if __name__ == "__main__":
    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    signal.signal(signal.SIGINT, handle_shutdown)
    signal.signal(signal.SIGTERM, handle_shutdown)
    print("python server is running at port:", PORT)
    print("python server is running at port:", APP_RUN)

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(main())
    except KeyboardInterrupt:
        pass
    finally:
        # 清理所有挂起的任务
        pending = asyncio.all_tasks(loop)
        for task in pending:
            task.cancel()
        if pending:
            loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
        loop.close()
    # isDebug = True if IS_DEBUG == "true" else False
    # uvicorn.run(
    #     app=APP_RUN,
    #     host=APP_HOST,
    #     port=int(PORT),
    #     reload=isDebug,
    #     loop="auto",
    # )
