import asyncio
import logging
import sys

from tool_agent.config import settings
from tool_agent.router.agent import Router
from tool_agent.service.session import SessionManager

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(name)s] %(levelname)s: %(message)s"
)
logger = logging.getLogger(__name__)


async def main():
    logger.info("正在初始化 Router（RouterAgent）...")
    router = Router()

    logger.info("正在初始化 SessionManager...")
    session_mgr = SessionManager(router)
    router.set_session_manager(session_mgr)

    router.create_app(session_manager=session_mgr)
    port = settings.fastapi_port

    try:
        # 启动 IM Client（可选，失败不影响 HTTP）
        try:
            await session_mgr.start_im(
                contact_id="tool_agent",
                server_url=os.environ.get("IM_SERVER_URL", "ws://localhost:8105"),
            )
        except Exception as e:
            logger.warning(f"IM Client 启动失败（HTTP 不受影响）: {e}")

        logger.info(f"正在启动 FastAPI，端口 {port}...")
        logger.info("对外接口: /health, /tools, /run_tool, /chat")
        await router.start(port=port)
    except Exception as e:
        logger.error(f"启动失败: {e}")
    finally:
        logger.info("正在停止所有服务...")
        await session_mgr.stop_im()
        router.stop_all()


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

    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("\n正在关闭...")
