"""
Knowledge Manager Agent - 启动脚本

作为独立的 IM Client 运行，监听并处理知识库查询和保存请求。
"""

import asyncio
import json
import logging
import os
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from dotenv import load_dotenv
load_dotenv()

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


async def main():
    """启动 Knowledge Manager Agent"""

    # 配置
    contact_id = os.getenv("KNOWLEDGE_MANAGER_CONTACT_ID", "knowledge_manager")
    server_url = os.getenv("IM_SERVER_URL", "ws://localhost:8005")
    chat_id = "main"

    logger.info(f"正在启动 Knowledge Manager...")
    logger.info(f"  - Contact ID: {contact_id}")
    logger.info(f"  - Server: {server_url}")
    logger.info(f"  - Chat ID: {chat_id}")

    # 导入 IM Client
    try:
        sys.path.insert(0, str(Path(__file__).parent.parent.parent / "im-client"))
        from client import IMClient
    except ImportError as e:
        logger.error(f"无法导入 IM Client: {e}")
        return

    # 创建 IM Client
    client = IMClient(
        contact_id=contact_id,
        server_url=server_url,
        data_dir=Path.home() / ".knowhub" / "im_data"
    )

    # 连接到服务器
    try:
        await client.connect(chat_id=chat_id)
        logger.info("✅ 已连接到 IM Server")
    except Exception as e:
        logger.error(f"连接失败: {e}")
        return
