"""Dynamic LLM-based intent handler for AKS DevOps."""

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from typing import Dict, Any, Tuple, Optional
from unishell.core.intent import LLMIntentClassifier, LLMParameterExtractor


class DynamicAKSIntentHandler:
    """Fully dynamic intent handler using local LLM."""
    
    def __init__(self, llm_client, model_name: str, action_registry: Dict[str, Any]):
        self.llm_client = llm_client
        self.model_name = model_name
        self.action_registry = action_registry
        
        available_actions = list(action_registry.keys())
        
        self.intent_classifier = LLMIntentClassifier(
            llm_client=llm_client,
            confidence_threshold=0.6,
            model_name=model_name,
            available_actions=available_actions
        )
        
        self.param_extractor = LLMParameterExtractor(
            llm_client=llm_client,
            confidence_threshold=0.6,
            model_name=model_name
        )
    
    def parse_intent(self, user_input: str) -> Tuple[Optional[str], Dict[str, Any], float]:
        """Parse intent using LLM."""
        import asyncio
        return asyncio.run(self._parse_intent_async(user_input))
    
    async def _parse_intent_async(self, user_input: str) -> Tuple[Optional[str], Dict[str, Any], float]:
        """Parse intent using LLM asynchronously."""
        try:
            # Quick keyword check for common misclassifications
            user_lower = user_input.lower()
            if "deploy" in user_lower and "path" in user_lower and "create service" not in user_lower:
                # Force deploy_application for "deploy ... path" patterns
                action = self.action_registry.get("deploy_application")
                if action:
                    param_result = await self.param_extractor.extract(
                        user_input=user_input,
                        action_id="deploy_application",
                        required_params=action.required_params,
                        context={}
                    )
                    return "deploy_application", param_result.parameters, 0.95
            
            intent_result = await self.intent_classifier.classify(user_input, {})
            
            if intent_result.needs_clarification or intent_result.action_id == "unknown":
                return None, {}, intent_result.confidence
            
            action = self.action_registry.get(intent_result.action_id)
            if not action:
                return None, {}, 0.0
            
            param_result = await self.param_extractor.extract(
                user_input=user_input,
                action_id=intent_result.action_id,
                required_params=action.required_params,
                context={}
            )
            
            return intent_result.action_id, param_result.parameters, intent_result.confidence
        except Exception as e:
            return None, {}, 0.0
    
    def validate_parameters(self, intent_id: str, params: Dict[str, Any]) -> Tuple[bool, str]:
        """Validate parameters."""
        action = self.action_registry.get(intent_id)
        if not action:
            return False, f"Unknown action: {intent_id}"
        
        missing = [p for p in action.required_params if p not in params]
        if missing:
            return False, f"Missing required parameters: {', '.join(missing)}"
        
        return True, ""
