"""
MLL Intake Supervisor Agent - Central Orchestrator
"""

from typing import Dict, Any, Optional
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).parent.parent))
from agents.base_agent import BaseAgent
from models.schemas import AgentType, AgentResponse, ConversationState, Intent, RequestType
from utils.semantic_classifier import classify_request


class SupervisorAgent(BaseAgent):
    """Supervisor Agent - Central Orchestrator"""
    
    def __init__(self):
        super().__init__(AgentType.SUPERVISOR)
        self.tools = ['route_to_agent', 'update_state', 'escalate_to_human']
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Intake Supervisor Agent, the central orchestrator for IT service requests.

Your role is to:
1. Welcome users and understand their needs
2. Route requests to the appropriate specialized agent
3. Maintain context across the conversation

Available agents:
- Intake Agent: For new IT service requests
- Network Agent: For network/firewall requests
- Incident Agent: For break-fix issues
- Access Agent: For application access
- Status Agent: For checking request status
- Knowledge Agent: For process questions"""
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process user message and determine routing"""
        
        # Classify the request
        classification = classify_request(user_message, state.collected_fields)
        state.classification = classification
        state.current_intent = classification.intent
        
        # Determine next agent
        next_agent = self._determine_routing(classification, state)
        
        # Generate response
        if len(state.messages) == 0:
            response_message = self._generate_welcome()
        else:
            response_message = self._generate_routing_response(user_message, classification, next_agent, state)
        
        return AgentResponse(
            agent=self.agent_type,
            message=response_message,
            next_agent=next_agent,
            state_updates={
                'classification': classification.model_dump(),
                'current_intent': classification.intent.value
            },
            confidence=classification.confidence
        )
    
    def _determine_routing(self, classification, state: ConversationState) -> Optional[AgentType]:
        """Determine which agent should handle the request"""
        intent = classification.intent
        request_type = classification.request_type
        
        # Route based on intent
        if intent == Intent.REPORT_INCIDENT:
            return AgentType.INCIDENT
        elif intent == Intent.CHECK_STATUS:
            return AgentType.STATUS
        elif intent == Intent.GET_ACCESS:
            return AgentType.ACCESS
        elif intent == Intent.GET_HELP:
            return AgentType.KNOWLEDGE
        
        # Route based on request type
        if request_type == RequestType.NETWORK:
            return AgentType.NETWORK
        elif request_type == RequestType.INCIDENT:
            return AgentType.INCIDENT
        elif request_type == RequestType.ACCESS:
            return AgentType.ACCESS
        elif request_type == RequestType.STATUS:
            return AgentType.STATUS
        elif request_type == RequestType.INTAKE:
            return AgentType.INTAKE
        
        return None
    
    def _generate_welcome(self) -> str:
        return """👋 **Welcome to MLL Intake Assistant!**

I can help you with:

• **New IT Service Requests** - Submit a Solution Intake
• **Network/Firewall Requests** - Network changes  
• **Incident Reports** - Report issues with existing systems
• **Access Requests** - Get application access (TS ENGAGE, etc.)
• **Status Checks** - Track existing RITM or Jira tickets
• **Process Help** - Learn about intake procedures

How can I help you today?"""
    
    def _generate_routing_response(self, user_message: str, classification, next_agent, state) -> str:
        """Generate response based on routing decision"""
        
        if next_agent is None:
            return """I want to make sure I help you correctly. Could you tell me more about what you need?

• Are you requesting something **new** that doesn't exist yet?
• Is something that was **working before now broken**?
• Do you need **network or firewall** changes?
• Do you need **access** to an application?
• Are you checking on an **existing request**?"""
        
        agent_descriptions = {
            AgentType.INTAKE: "help you submit a new Solution Intake request",
            AgentType.NETWORK: "assist with your network/firewall request",
            AgentType.INCIDENT: "help report this incident",
            AgentType.ACCESS: "help you get application access",
            AgentType.STATUS: "check on your request status",
            AgentType.KNOWLEDGE: "answer your questions about our processes"
        }
        
        description = agent_descriptions.get(next_agent, "assist you")
        
        # Add detected context
        context_parts = []
        if classification.entities.get('sites'):
            site = classification.entities['sites'][0]
            context_parts.append(f"Site: {site['name']}")
        if classification.entities.get('ritm_numbers'):
            context_parts.append(f"RITM: {classification.entities['ritm_numbers'][0]}")
        
        context_str = ""
        if context_parts:
            context_str = f"\n\n📌 Detected: {', '.join(context_parts)}"
        
        return f"I understand. Let me {description}.{context_str}"


supervisor_agent = SupervisorAgent()
