"""
MLL Access Agent - Application Access Requests
"""

import re
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, AccessRequest


class AccessAgent(BaseAgent):
    """Access Agent - Application Access Requests"""
    
    def __init__(self):
        super().__init__(AgentType.ACCESS)
        self.tools = ['create_access_request']
        self.required_fields = ['application', 'login_id', 'justification']
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Access Agent, handling application access requests.

For TS ENGAGE-PROD Access:
1. Submit in IRIS: "Create a new account for an application"
2. Application CI: TS ENGAGE - PROD
3. Application Login ID: Your Network Account
4. Account Type: Standard Account"""
    
    def get_required_fields(self) -> List[str]:
        return self.required_fields
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process access request"""
        
        if not state.access_request:
            state.access_request = AccessRequest()
        
        # Check for TS ENGAGE
        if self._is_ts_engage(user_message, state):
            return self._handle_ts_engage(user_message, state)
        
        # Extract fields
        extracted = self._extract_fields(user_message, state)
        for field, value in extracted.items():
            state.collected_fields[field] = value
        
        # Check missing
        missing = [f for f in self.required_fields if f not in state.collected_fields]
        
        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
        
        # Check confirmation
        if state.awaiting_confirmation and any(c in user_message.lower() for c in ['confirm', 'yes', 'submit']):
            response_message = self._create_access_request(state)
            state.completed = True
            next_agent = AgentType.SUPERVISOR
        
        return AgentResponse(
            agent=self.agent_type,
            message=response_message,
            next_agent=next_agent,
            state_updates={'collected_fields': state.collected_fields}
        )
    
    def _is_ts_engage(self, message: str, state: ConversationState) -> bool:
        return any(ind in message.lower() for ind in ['ts engage', 'tsengage', 'asoe'])
    
    def _handle_ts_engage(self, message: str, state: ConversationState) -> AgentResponse:
        state.collected_fields['application'] = 'TS ENGAGE-PROD'
        state.collected_fields['application_ci'] = 'TS ENGAGE - PROD'
        state.collected_fields['account_type'] = 'Standard Account'
        
        if 'login_id' not in state.collected_fields:
            return AgentResponse(
                agent=self.agent_type,
                message="""**TS ENGAGE-PROD Access Request**

To get access:
1. Go to IRIS → "Create a new account for an application"
2. Application CI: TS ENGAGE - PROD
3. Application Login ID: Your Network Account
4. Account Type: Standard Account

**What is your Network Account/Login ID?**""",
                next_agent=None,
                state_updates={'collected_fields': state.collected_fields}
            )
        
        if 'justification' not in state.collected_fields:
            return AgentResponse(
                agent=self.agent_type,
                message="**Please provide a brief justification for TS ENGAGE-PROD access:**\n\nWhy do you need access? What tasks will you perform?",
                next_agent=None,
                state_updates={'collected_fields': state.collected_fields}
            )
        
        return AgentResponse(
            agent=self.agent_type,
            message=self._generate_summary(state),
            next_agent=None,
            state_updates={'collected_fields': state.collected_fields}
        )
    
    def _extract_fields(self, message: str, state: ConversationState) -> Dict[str, Any]:
        extracted = {}
        
        # Extract login ID
        id_match = re.search(r'\b([A-Za-z]{2,3}\d{5,7})\b', message)
        if id_match:
            extracted['login_id'] = id_match.group(1)
        
        # If longer message, might be justification
        if len(message) > 30 and 'justification' not in state.collected_fields:
            if '?' not in message:
                extracted['justification'] = message
        
        return extracted
    
    def _generate_question(self, field: str) -> str:
        questions = {
            'application': "**Which application do you need access to?**",
            'login_id': "**What is your Network Account / Login ID?**",
            'justification': "**Why do you need access?**\n\nPlease provide a brief justification."
        }
        return questions.get(field, f"Please provide {field}")
    
    def _generate_summary(self, state: ConversationState) -> str:
        cf = state.collected_fields
        
        summary = "**✅ Access Request Summary**\n\n"
        summary += f"**Application**: {cf.get('application', 'N/A')}\n"
        summary += f"**Login ID**: {cf.get('login_id', 'N/A')}\n"
        summary += f"**Justification**: {cf.get('justification', 'N/A')[:50]}...\n"
        summary += "\n---\n**Type 'confirm' to submit**"
        
        return summary
    
    def _create_access_request(self, state: ConversationState) -> str:
        ritm = f"RITM{random.randint(100000000000, 999999999999)}"
        state.created_tickets.append(ritm)
        
        return f"""**🎉 Access Request Submitted!**

**RITM**: {ritm}
**Application**: {state.collected_fields.get('application')}
**Status**: Pending Approval

**Timeline**: 1-3 business days

Track at: {ritm} in IRIS"""


access_agent = AccessAgent()
