"""Dynamic AKS DevOps Agent using local LLM."""

from typing import Dict, Any, Optional
from .dynamic_intent_handler import DynamicAKSIntentHandler
from .command_executor import AKSCommandExecutor
from .dynamic_action_definitions import DynamicAKSActionRegistry


class DynamicAKSAgent:
    """Fully dynamic DevOps agent using local LLM for intent understanding."""
    
    def __init__(self, 
                 llm_client,
                 model_name: str,
                 default_namespace: str = "default",
                 default_registry: str = None,
                 auto_confirm: bool = False,
                 min_confidence: float = 0.6):
        """Initialize dynamic agent.
        
        Args:
            llm_client: OpenAI client instance
            model_name: Model name to use
            default_namespace: Default Kubernetes namespace
            default_registry: Default Azure Container Registry URL
            auto_confirm: Auto-confirm actions without user prompt
            min_confidence: Minimum confidence threshold
        """
        self.action_registry = DynamicAKSActionRegistry.get_actions()
        self.intent_handler = DynamicAKSIntentHandler(llm_client, model_name, self.action_registry)
        self.executor = AKSCommandExecutor(default_namespace, default_registry, llm_client, model_name)
        self.auto_confirm = auto_confirm
        self.min_confidence = min_confidence
        self.history = []
    
    def process_command(self, user_input: str) -> Dict[str, Any]:
        """Process natural language command using LLM."""
        # Parse intent using LLM
        intent_id, params, confidence = self.intent_handler.parse_intent(user_input)
        
        result = {
            "user_input": user_input,
            "intent": intent_id,
            "parameters": params,
            "confidence": confidence,
            "success": False,
            "message": "",
            "output": "",
            "error": ""
        }
        
        if not intent_id:
            result["message"] = "Could not understand the command. Please rephrase."
            return result
        
        if confidence < self.min_confidence:
            result["message"] = f"Low confidence ({confidence:.2f}). Please provide more details."
            return result
        
        is_valid, error_msg = self.intent_handler.validate_parameters(intent_id, params)
        if not is_valid:
            result["message"] = error_msg
            return result
        
        action = self.action_registry.get(intent_id)
        if not action:
            result["message"] = f"Action not found: {intent_id}"
            return result
        
        if action.execution.requires_confirmation and not self.auto_confirm:
            result["message"] = f"Ready to execute: {action.description}"
            result["requires_confirmation"] = True
            result["action_details"] = {
                "action_id": intent_id,
                "description": action.description,
                "parameters": params,
                "risk_level": action.risk_level.value
            }
            return result
        
        return self.execute_action(intent_id, params)
    
    def execute_action(self, intent_id: str, params: Dict[str, Any]) -> Dict[str, Any]:
        """Execute action."""
        action = self.action_registry.get(intent_id)
        
        result = {
            "intent": intent_id,
            "parameters": params,
            "success": False,
            "message": "",
            "output": "",
            "error": ""
        }
        
        success, stdout, stderr = self.executor.execute_action(intent_id, params)
        
        result["success"] = success
        result["output"] = stdout
        result["error"] = stderr
        result["message"] = f"{'Successfully' if success else 'Failed to'} executed: {action.description}"
        
        self.history.append(result)
        return result
    
    def get_available_actions(self) -> Dict[str, str]:
        """Get available actions."""
        return {aid: a.description for aid, a in self.action_registry.items()}
