"""
MLL Knowledge Agent - Documentation and Process Guidance
"""

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
from utils.embeddings import search_similar


class KnowledgeAgent(BaseAgent):
    """Knowledge Agent - Documentation and Process Guidance"""
    
    def __init__(self):
        super().__init__(AgentType.KNOWLEDGE)
        self.tools = ['search_knowledge_base']
        self.knowledge_base = self._build_knowledge_base()
    
    def _build_knowledge_base(self) -> Dict[str, str]:
        return {
            "intake_process": """**MLLF Intake Process**

1. Site ID (4-digit identifier)
2. ZCode (business unit)
3. Select Capability Center
4. Enter Nexus ID (if required)
5. Describe Business Problem and Value
6. Submit request
7. Receive IRIS RITM number
8. Request automates to Jira Epic""",

            "intake_vs_incident": """**Intake vs Incident**

| Intake Request | Incident |
|----------------|----------|
| Request for new demand | Unplanned interruption |
| Never worked before | Was working, now broken |
| Enhancement/upgrade | Quality reduction |

**Rule**: 
- "Never worked" → Intake
- "Was working, now broken" → Incident""",

            "capability_centers": """**Capability Centers**

1. **Agile Demand** (Requires Nexus ID)
   - Simple scope, non-project

2. **Approved Project Demand** (Requires Nexus ID)
   - Part of portfolio project

3. **Request for Estimate**
   - BP estimate request

4. **TS Internal Demand**
   - TS-driven work (e.g., Network TLM)""",

            "network_process": """**MLL Network Request Process**

**CRITICAL**: Start with MLL Intake Request first!

1. Submit MLL Solution Intake
2. Jira Epic created
3. Service owner gathers user stories
4. If networking needed → Create Network Jira card
5. MLL Network RITM submitted
6. Reviewed on triage call
7. Upon approval, assigned to network team

**Priorities**:
- P1: Urgent/Emergency
- P2: High Priority
- P3: Standard (default)
- P4: Deferred""",

            "ts_engage_access": """**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

Reference: KB000010097493"""
        }
    
    def get_system_prompt(self) -> str:
        return """You are the MLL Knowledge Agent, an expert on MLL IT service processes."""
    
    def process(self, user_message: str, state: ConversationState) -> AgentResponse:
        """Process knowledge query"""
        
        # Find relevant topics
        topics = self._find_relevant_topics(user_message)
        
        # Search similar requests
        similar = search_similar(user_message, top_k=3)
        
        # Generate response
        response_message = self._generate_response(user_message, topics, similar)
        
        # Check if user wants action
        next_agent = self._check_action_intent(user_message)
        
        return AgentResponse(
            agent=self.agent_type,
            message=response_message,
            next_agent=next_agent,
            state_updates={}
        )
    
    def _find_relevant_topics(self, query: str) -> List[str]:
        query_lower = query.lower()
        relevant = []
        
        topic_keywords = {
            'intake_process': ['intake', 'submit', 'request', 'how to', 'process'],
            'intake_vs_incident': ['incident', 'vs', 'difference', 'broken'],
            'capability_centers': ['capability', 'agile', 'project demand', 'nexus'],
            'network_process': ['network', 'firewall', 'lan', 'wan'],
            'ts_engage_access': ['access', 'ts engage', 'asoe', 'login']
        }
        
        for topic, keywords in topic_keywords.items():
            if any(kw in query_lower for kw in keywords):
                relevant.append(topic)
        
        return relevant
    
    def _generate_response(self, query: str, topics: List[str], similar: List[Dict[str, Any]]) -> str:
        parts = []
        
        if topics:
            for topic in topics[:2]:
                if topic in self.knowledge_base:
                    parts.append(self.knowledge_base[topic])
        
        if not topics:
            parts.append("""**MLL IT Services - Quick Guide**

I can help with:

1. **Submitting Requests** - Solution Intake, Network, Access
2. **Understanding Processes** - Intake vs Incident, Capability Centers
3. **Tracking Requests** - RITM and Jira status

What would you like to know more about?""")
        
        if similar:
            similar_section = "\n\n**Related Historical Requests**:\n"
            for req in similar[:3]:
                req_id = req.get('id', 'N/A')
                score = req.get('similarity_score', 0)
                similar_section += f"- {req_id} ({int(score*100)}% similar)\n"
            parts.append(similar_section)
        
        parts.append("\n---\nWould you like me to help you with any of these processes?")
        
        return "\n\n".join(parts)
    
    def _check_action_intent(self, query: str) -> AgentType:
        query_lower = query.lower()
        
        if any(w in query_lower for w in ['submit', 'create', 'new intake']):
            return AgentType.INTAKE
        if any(w in query_lower for w in ['network request', 'firewall']):
            return AgentType.NETWORK
        if any(w in query_lower for w in ['get access', 'need access']):
            return AgentType.ACCESS
        if any(w in query_lower for w in ['check status', 'where is']):
            return AgentType.STATUS
        
        return None


knowledge_agent = KnowledgeAgent()
