"""
Router Agent for Task Manager MCP Servers

Adapted from the original project's RouterAgent for use in MCP servers.
This agent routes user requests to appropriate handlers based on intent analysis.
"""

import os
import json
import requests
from typing import Dict, Optional
import logging
import re


# Configure logging
logging.basicConfig(level=logging.INFO, 
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("RouterAgent")


class RouterAgent:
    """
    一个AI智能体，其唯一职责是根据用户的输入，判断用户的意图，
    并决定应该将请求路由到哪个下游AI智能体。
    """
    
    SYSTEM_PROMPT = """
You are a highly intelligent routing agent for an AI project management assistant. Your primary goal is to analyze the user's message and classify it into one of two distinct categories.

**Your job is to return a JSON object with a single key "tool" and one of these values:**

1.  **`general_conversation`**: Use this for most interactions, including:
    - Starting new projects or discussing ideas
    - Asking questions about project management
    - Requesting analysis, recommendations, or planning
    - General conversation about tasks and projects
    - Example: "I want to build a mobile app"
    - Example: "Help me plan my project timeline"
    - Example: "What should I work on next?"

2.  **`command_execution`**: Use this ONLY for specific, direct commands to manipulate existing tasks or projects (like updating, deleting, listing).
    - Example: "Update task T-123 to be 'in progress'."
    - Example: "Show me all the tasks."
    - Example: "Delete project 'Old Project'."

Your decision process is simple: If it looks like a direct command to view or change existing data, use `command_execution`. For everything else, including starting a new project plan, use `general_conversation`.
"""

    def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
        """
        初始化RouterAgent。
        """
        self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
        self.base_url = base_url or os.environ.get("OPENAI_BASE_URL", "https://api.openai.com")
        
        # 确保base_url没有尾部斜杠，避免URL拼接问题
        if self.base_url and self.base_url.endswith('/'):
            self.base_url = self.base_url[:-1]
            
        logger.info(f"RouterAgent initialized with base_url: {self.base_url}")
        
        # 验证API密钥是否存在
        if not self.api_key:
            logger.error("API密钥未设置，请确保OPENAI_API_KEY环境变量已设置")
            
        # 验证base_url是否有效
        if not self.base_url:
            logger.error("API基础URL未设置，请确保OPENAI_BASE_URL环境变量已设置")

    def decide_tool(self, user_input: str) -> dict:
        """
        Analyzes user input and decides which tool to use.
        """
        try:
            # 构建完整的API URL
            api_url = f"{self.base_url}/v1/chat/completions"
            logger.info(f"Making request to: {api_url}")
            
            # 准备请求数据
            payload = {
                "model": "gpt-4-turbo",
                "messages": [
                    {"role": "system", "content": self.SYSTEM_PROMPT},
                    {"role": "user", "content": user_input}
                ],
                "response_format": {"type": "json_object"},
                "temperature": 0
            }
            
            # 准备请求头
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.api_key}"
            }
            
            # 发送请求
            response = requests.post(api_url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            
            # 解析响应
            response_data = response.json()
            content = response_data.get("choices", [{}])[0].get("message", {}).get("content", "")
            
            if not content:
                logger.error("LLM返回了空内容")
                return {"tool": "general_conversation"}
            
            try:
                result = json.loads(content)
                tool = result.get("tool", "general_conversation")
                logger.info(f"Router decision: {tool}")
                return {"tool": tool}
            except json.JSONDecodeError as e:
                logger.error(f"JSON解析失败: {e}, content: {content}")
                return {"tool": "general_conversation"}
                
        except requests.exceptions.RequestException as e:
            logger.error(f"API请求失败: {e}")
            return {"tool": "general_conversation"}
        except Exception as e:
            logger.error(f"RouterAgent发生未知错误: {e}")
            return {"tool": "general_conversation"}
