"""
MLL Status Agent - Ticket Status Tracking
"""

import re
from typing import Dict, Any
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, StatusQuery
from utils.data_loader import data_loader


class StatusAgent(BaseAgent):
    """Status Agent - Ticket Status Tracking"""
    
    def __init__(self):
        super().__init__(AgentType.STATUS)
        self.tools = ['lookup_ritm_status', 'lookup_jira_status']
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Status Agent, providing status updates on IT service requests.

Can look up:
- RITM numbers (e.g., RITM000023615895)
- Jira keys (e.g., ABFZ-97929)"""
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process status query"""
        
        if not state.status_query:
            state.status_query = StatusQuery()
        
        # Extract ticket IDs
        extracted = self._extract_ticket_ids(user_message)
        for field, value in extracted.items():
            state.collected_fields[field] = value
        
        # Look up status
        if extracted.get('ritm_number'):
            response_message = self._lookup_ritm(extracted['ritm_number'])
        elif extracted.get('jira_key'):
            response_message = self._lookup_jira(extracted['jira_key'])
        else:
            response_message = self._request_ticket()
        
        return AgentResponse(
            agent=self.agent_type,
            message=response_message,
            next_agent=AgentType.SUPERVISOR if 'anything else' in response_message.lower() else None,
            state_updates={'collected_fields': state.collected_fields}
        )
    
    def _extract_ticket_ids(self, message: str) -> Dict[str, str]:
        extracted = {}
        message_upper = message.upper()
        
        # Extract RITM
        ritm_match = re.search(r'RITM\d{12,15}', message_upper)
        if ritm_match:
            extracted['ritm_number'] = ritm_match.group(0)
        
        # Extract Jira key
        jira_match = re.search(r'ABFZ-\d+', message_upper)
        if jira_match:
            extracted['jira_key'] = jira_match.group(0)
        
        return extracted
    
    def _lookup_ritm(self, ritm_number: str) -> str:
        result = data_loader.search_iris_by_ritm(ritm_number)
        
        if result:
            short_desc = result.get('short_description', result.get('Short description', 'N/A'))
            stage = result.get('stage', result.get('Stage', 'N/A'))
            state = result.get('state', result.get('State', 'N/A'))
            
            response = f"""**📋 RITM Status: {ritm_number}**

**Description**: {short_desc}
**Stage**: {stage}
**State**: {state}

"""
            
            state_lower = str(state).lower()
            if 'closed' in state_lower or 'completed' in state_lower:
                response += "✅ This request has been completed.\n"
            elif 'progress' in state_lower:
                response += "🔄 This request is in progress.\n"
            elif 'pending' in state_lower:
                response += "⏳ This request is pending.\n"
            
            response += "\nIs there anything else I can help you with?"
            return response
        
        return f"""**🔍 RITM: {ritm_number}**

I couldn't find this RITM in my dataset.

**Try**:
- Check IRIS directly
- Verify the RITM number
- Look for a linked Jira Epic

Would you like to try another ticket number?"""
    
    def _lookup_jira(self, jira_key: str) -> str:
        result = data_loader.search_epics_by_key(jira_key)
        
        if result:
            summary = result.get('Summary', result.get('summary', 'N/A'))
            status = result.get('Status', result.get('status', 'N/A'))
            
            response = f"""**📋 Jira: {jira_key}**

**Summary**: {summary}
**Status**: {status}

"""
            
            status_lower = str(status).lower()
            if 'completed' in status_lower or 'done' in status_lower:
                response += "✅ This Epic has been completed.\n"
            elif 'progress' in status_lower:
                response += "🔄 Work is in progress.\n"
            
            response += "\nIs there anything else I can help you with?"
            return response
        
        return f"""**🔍 Jira: {jira_key}**

I couldn't find this ticket.

**Try**:
- Check Jira directly
- Verify the key format (ABFZ-XXXXX)

Would you like to try another?"""
    
    def _request_ticket(self) -> str:
        return """**🔍 Status Check**

Please provide:

1. **RITM Number**: e.g., RITM000023615895
2. **Jira Key**: e.g., ABFZ-97929

Which ticket would you like to look up?"""


status_agent = StatusAgent()
