"""
AI配置示例
"""
from pathlib import Path
from src.ai import AIClient
from src.ai.base import ModelConfig, ModelProvider
from src.ai.skills import SkillsManager
from src.ai.mcp import MCPManager
from src.ai.mcp.servers import FileSystemMCPServer


async def setup_ai_client():
    """设置AI客户端"""
    
    # 1. 创建模型配置
    config = ModelConfig(
        provider=ModelProvider.OPENAI,
        model_name="gpt-4",
        api_key="your_api_key_here",
        temperature=0.7,
        max_tokens=4096
    )
    
    # 2. 初始化AI客户端
    client = AIClient(config, data_dir=Path("data/ai"))
    
    # 3. 设置人格
    client.set_personality("default")
    
    # 4. 加载Skills
    skills_manager = SkillsManager(Path("skills"))
    await skills_manager.load_all_skills()
    
    # 将Skills的工具注册到AI客户端
    for tool_name, tool_func in skills_manager.get_all_tools().items():
        # 解析工具名称和描述
        parts = tool_name.split('.')
        if len(parts) == 2:
            skill_name, func_name = parts
            client.register_tool(
                name=tool_name,
                description=f"{skill_name}技能的{func_name}工具",
                parameters={
                    "type": "object",
                    "properties": {},
                    "required": []
                },
                function=tool_func
            )
    
    # 5. 设置MCP
    mcp_manager = MCPManager(Path("config/mcp.json"))
    
    # 注册文件系统服务器
    fs_server = FileSystemMCPServer(root_path=Path("data"))
    await mcp_manager.register_server(fs_server)
    
    # 获取MCP工具并注册到AI客户端
    mcp_tools = await mcp_manager.get_all_tools_for_ai()
    for tool in mcp_tools:
        func_info = tool['function']
        
        # 创建工具执行函数
        async def execute_mcp_tool(**kwargs):
            return await mcp_manager.execute_tool(func_info['name'], kwargs)
        
        client.register_tool(
            name=func_info['name'],
            description=func_info['description'],
            parameters=func_info['parameters'],
            function=execute_mcp_tool
        )
    
    return client


async def example_usage():
    """使用示例"""
    
    # 设置客户端
    client = await setup_ai_client()
    
    # 示例1: 基础对话
    print("=== 示例1: 基础对话 ===")
    response = await client.chat(
        user_id="user123",
        user_message="你好，介绍一下你自己",
        use_memory=True
    )
    print(f"AI: {response}\n")
    
    # 示例2: 使用记忆
    print("=== 示例2: 使用记忆 ===")
    await client.chat(
        user_id="user123",
        user_message="我喜欢编程，特别是Python",
        use_memory=True
    )
    
    response = await client.chat(
        user_id="user123",
        user_message="我刚才说我喜欢什么？",
        use_memory=True
    )
    print(f"AI: {response}\n")
    
    # 示例3: 切换人格
    print("=== 示例3: 切换人格 ===")
    client.set_personality("tech_expert")
    response = await client.chat(
        user_id="user123",
        user_message="如何优化Python代码性能？",
        use_memory=False
    )
    print(f"AI (技术专家): {response}\n")
    
    # 示例4: 创建长任务
    print("=== 示例4: 创建长任务 ===")
    
    # 注册任务动作
    async def step1():
        print("执行步骤1...")
        return "步骤1完成"
    
    async def step2():
        print("执行步骤2...")
        return "步骤2完成"
    
    client.task_manager.register_action("step1", step1)
    client.task_manager.register_action("step2", step2)
    
    # 创建任务
    task_id = await client.create_long_task(
        user_id="user123",
        title="测试任务",
        description="测试长任务功能",
        steps=[
            {"description": "第一步", "action": "step1", "params": {}},
            {"description": "第二步", "action": "step2", "params": {}}
        ]
    )
    
    # 执行任务
    async def on_progress(tid, progress, message):
        print(f"进度: {progress*100:.0f}% - {message}")
    
    await client.start_task(task_id, progress_callback=on_progress)
    
    # 查询状态
    status = client.get_task_status(task_id)
    print(f"任务状态: {status}\n")


if __name__ == "__main__":
    import asyncio
    asyncio.run(example_usage())
