"""
MLL Network Agent - Network/Firewall 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, NetworkRequest, Priority
from config import NETWORK_PRIORITIES


class NetworkAgent(BaseAgent):
    """Network Agent - Network/Firewall Requests"""
    
    def __init__(self):
        super().__init__(AgentType.NETWORK)
        self.tools = ['validate_intake_ritm', 'create_network_ritm']
        self.required_fields = ['parent_ritm', 'network_type', 'priority']
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Network Agent, handling network and firewall requests.

CRITICAL: An MLL Intake Request is required BEFORE submitting a Network request.

Network Types: LAN/WAN, Firewall MACD, Switch, VLAN

Priority Levels:
- P1: Urgent/Emergency
- P2: High Priority
- P3: Standard (default)
- P4: Deferred"""
    
    def get_required_fields(self) -> List[str]:
        return self.required_fields
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process network request"""
        
        if not state.network_request:
            state.network_request = NetworkRequest()
        
        # Extract fields
        extracted = self._extract_fields(user_message)
        for field, value in extracted.items():
            state.collected_fields[field] = value
        
        # Check prerequisite
        if 'parent_ritm' not in state.collected_fields:
            return AgentResponse(
                agent=self.agent_type,
                message=self._request_parent_ritm(),
                next_agent=None,
                state_updates={}
            )
        
        # Check missing fields
        missing = [f for f in ['network_type', 'priority'] 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_network_ritm(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 _extract_fields(self, message: str) -> Dict[str, Any]:
        """Extract network fields"""
        extracted = {}
        message_lower = message.lower()
        message_upper = message.upper()
        
        # Extract RITM
        ritm_match = re.search(r'RITM\d{12,15}', message_upper)
        if ritm_match:
            extracted['parent_ritm'] = ritm_match.group(0)
        
        # Extract network type
        network_types = []
        if 'lan' in message_lower or 'wan' in message_lower:
            network_types.append('LAN/WAN')
        if 'firewall' in message_lower:
            network_types.append('Firewall')
        if 'switch' in message_lower:
            network_types.append('Switch')
        if 'vlan' in message_lower:
            network_types.append('VLAN')
        if network_types:
            extracted['network_type'] = network_types
        
        # Extract priority
        for priority in ['P1', 'P2', 'P3', 'P4']:
            if priority in message_upper:
                extracted['priority'] = Priority(priority)
                break
        
        return extracted
    
    def _request_parent_ritm(self) -> str:
        return """**⚠️ MLL Intake RITM Required**

Before submitting a network request, you must have an existing MLL Intake RITM.

**Do you have an MLL Intake RITM?**

- If **yes**, please provide the RITM number (e.g., RITM000023615895)
- If **no**, I can help you create a Solution Intake first

Type 'create intake' to start a new one."""
    
    def _generate_question(self, field: str) -> str:
        questions = {
            'network_type': """**What type of network change?**

- **LAN/WAN** - Network modifications
- **Firewall** - Firewall rules (MACD)
- **Switch** - Switch configuration
- **VLAN** - VLAN setup""",
            
            'priority': """**What priority?**

- **P1** - Urgent/Emergency
- **P2** - High Priority
- **P3** - Standard (default)
- **P4** - Deferred"""
        }
        return questions.get(field, f"Please provide {field}")
    
    def _generate_summary(self, state: ConversationState) -> str:
        cf = state.collected_fields
        
        summary = "**✅ MLL Network Request Summary**\n\n"
        summary += f"**Parent RITM**: {cf.get('parent_ritm')}\n"
        summary += f"**Network Type**: {cf.get('network_type')}\n"
        summary += f"**Priority**: {cf.get('priority', 'P3')}\n"
        summary += "\n---\n**Type 'confirm' to submit**"
        
        return summary
    
    def _create_network_ritm(self, state: ConversationState) -> str:
        ritm = f"RITM{random.randint(100000000000, 999999999999)}"
        task = f"TASK{random.randint(10000000000, 99999999999)}"
        
        state.created_tickets.append(ritm)
        
        return f"""**🎉 Network Request Submitted!**

**Network RITM**: {ritm}
**Task**: {task}
**Linked to**: {state.collected_fields.get('parent_ritm')}

**Next Steps**:
1. Reviewed on triage call
2. Upon approval, assigned to network team
3. Network engineer will contact you"""


network_agent = NetworkAgent()
