"""
MLL Incident Agent - Break-Fix Issues
"""

import random
from typing import Dict, Any, List
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, IncidentReport


class IncidentAgent(BaseAgent):
    """Incident Agent - Break-Fix Issues"""
    
    def __init__(self):
        super().__init__(AgentType.INCIDENT)
        self.tools = ['create_incident', 'search_known_issues']
        self.required_fields = ['affected_system', 'impact']
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Incident Agent, handling break-fix issues.

Incident vs Intake:
- Intake: Something that has never worked before
- Incident: Existing functionality that suddenly broke"""
    
    def get_required_fields(self) -> List[str]:
        return self.required_fields
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process incident report"""
        
        if not state.incident_report:
            state.incident_report = IncidentReport()
        
        # Check if actually an intake (new functionality request)
        if not state.collected_fields and self._is_actually_intake(user_message):
            return AgentResponse(
                agent=self.agent_type,
                message="**This sounds like a new request rather than an incident.**\n\nI'll redirect you to submit a Solution Intake instead.",
                next_agent=AgentType.INTAKE,
                state_updates={}
            )
        
        # Extract fields from message
        extracted = self._extract_fields(user_message)
        for field, value in extracted.items():
            state.collected_fields[field] = value
        
        # Check for confirmation first
        if state.awaiting_confirmation and any(c in user_message.lower() for c in ['confirm', 'yes', 'submit']):
            response_message = self._create_incident(state)
            state.completed = True
            state.missing_fields = []  # Clear missing fields
            return AgentResponse(
                agent=self.agent_type,
                message=response_message,
                next_agent=AgentType.SUPERVISOR,
                state_updates={'collected_fields': state.collected_fields, 'missing_fields': []}
            )
        
        # Check missing fields
        missing = [f for f in self.required_fields if f not in state.collected_fields]
        state.missing_fields = missing  # CRITICAL: Set missing fields for routing continuity
        
        if missing:
            response_message = self._generate_question(missing[0])
            next_agent = None
        else:
            response_message = self._generate_summary(state)
            state.awaiting_confirmation = True
            next_agent = None
        
        return AgentResponse(
            agent=self.agent_type,
            message=response_message,
            next_agent=next_agent,
            state_updates={'collected_fields': state.collected_fields, 'missing_fields': missing}
        )
    
    def _is_actually_intake(self, message: str) -> bool:
        intake_words = ['never worked', 'new feature', 'want to add', 'implement']
        incident_words = ['was working', 'stopped', 'broken', 'error', 'crashed']
        
        intake_score = sum(1 for w in intake_words if w in message.lower())
        incident_score = sum(1 for w in incident_words if w in message.lower())
        
        return intake_score > incident_score
    
    def _extract_fields(self, message: str) -> Dict[str, Any]:
        """Extract incident fields from message - PRODUCTION GRADE"""
        extracted = {}
        message_lower = message.lower()
        message_clean = message.strip()
        
        # Extract affected system - only from short, specific mentions
        system_patterns = {
            'TS ENGAGE': ['ts engage', 'tsengage', 'ts-engage', 'engage'],
            'JIRA': ['jira'],
            'IRIS': ['iris', 'servicenow'],
            'SAP': ['sap'],
            'NETWORK': ['network', 'wifi', 'internet', 'connection', 'connectivity'],
            'EMAIL': ['email', 'outlook', 'mail'],
        }
        
        for system, patterns in system_patterns.items():
            if any(p in message_lower for p in patterns):
                extracted['affected_system'] = system
                break
        
        # If no specific system found and it's a short message (likely answering "which system?")
        if 'affected_system' not in extracted and len(message_clean) < 30:
            # Short message might be the system name itself
            upper = message_clean.upper()
            if upper and not any(word in message_lower for word in ['user', 'affect', 'impact', 'broken']):
                extracted['affected_system'] = upper
        
        # Extract impact - be flexible but don't extract from system-only messages
        if len(message_clean) > 20 or any(word in message_lower for word in ['user', 'affect', 'impact', 'critical']):
            impact_patterns = {
                'Critical - Production impact': ['critical', 'urgent', 'production', 'emergency', 'p1', 'priority 1', 'blocking'],
                'Multiple users affected': ['multiple', 'all users', 'everyone', 'team', 'many users', 'warehouse', 'department', 'all staff', 'several people', 'users'],
                'Single user affected': ['just me', 'only i', 'my account', 'single user', 'only me']
            }
            
            for impact, patterns in impact_patterns.items():
                if any(p in message_lower for p in patterns):
                    extracted['impact'] = impact
                    break
            
            # If no specific impact found but message contains impact-like description
            if 'impact' not in extracted:
                impact_indicators = ['affected', 'impact', 'blocking', 'cannot', 'unable', 'down']
                if any(ind in message_lower for ind in impact_indicators):
                    extracted['impact'] = message_clean[:100]
        
        return extracted
    
    def _generate_question(self, field: str) -> str:
        questions = {
            'affected_system': "**Which system is affected?**\n\n(e.g., TS ENGAGE, Jira, SAP, Network)",
            'impact': "**What is the business impact?**\n\n- How many users affected?\n- Is this blocking critical work?"
        }
        return questions.get(field, f"Please provide {field}")
    
    def _generate_summary(self, state: ConversationState) -> str:
        cf = state.collected_fields
        
        summary = "**🔴 Incident Report Summary**\n\n"
        summary += f"**Affected System**: {cf.get('affected_system', 'N/A')}\n"
        summary += f"**Impact**: {cf.get('impact', 'N/A')}\n"
        summary += "\n---\n**Type 'confirm' to submit**"
        
        return summary
    
    def _create_incident(self, state: ConversationState) -> str:
        inc = f"INC{random.randint(10000000, 99999999)}"
        state.created_tickets.append(inc)
        
        return f"""**🎫 Incident Submitted!**

**Incident**: {inc}
**Status**: New

**Next Steps**:
1. Incident in queue
2. Technician will be assigned
3. Updates sent via email

For P1/P2, also call the Service Desk."""


incident_agent = IncidentAgent()
