"""Dynamic CLI using local LLM for intent understanding."""

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

from openai import OpenAI
from devops_agent.dynamic_aks_agent import DynamicAKSAgent


def print_result(result):
    """Print result."""
    print(f"\n{'='*60}")
    print(f"Intent: {result.get('intent', 'N/A')}")
    print(f"Confidence: {result.get('confidence', 0):.2f}")
    print(f"Parameters: {result.get('parameters', {})}")
    print(f"{'='*60}")
    print(f"Message: {result.get('message', '')}")
    
    if result.get('success'):
        print(f"\n✓ SUCCESS")
        if result.get('output'):
            print(f"\nOutput:\n{result['output']}")
    elif result.get('error'):
        print(f"\n✗ ERROR")
        print(f"\nError:\n{result['error']}")
    
    if result.get('requires_confirmation'):
        print(f"\n⚠ Risk Level: {result['action_details']['risk_level']}")
    print(f"{'='*60}\n")


def main():
    print("=== Dynamic AKS DevOps Agent (LLM-Powered) ===\n")
    """
    # Check kubectl connection first
    print("Checking Kubernetes connection...")
    try:
        result = subprocess.run(
            "kubectl cluster-info",
            shell=True,
            capture_output=True,
            timeout=5
        )
        if result.returncode != 0:
            print("\n✗ Kubernetes cluster not connected!")
            print("\nPlease connect to your AKS cluster first:")
            print("  az aks get-credentials --resource-group <your-rg> --name <your-cluster>")
            print("\nThen verify connection:")
            print("  kubectl cluster-info")
            print("  kubectl get nodes")
            return
        print("✓ Kubernetes connected\n")
    except Exception as e:
        print(f"\n✗ kubectl not found or not working: {e}")
        print("\nPlease install kubectl and connect to AKS first.")
        return
    """
    # Configure local LLM
    base_url = input("API Base URL [http://localhost:11434/v1]: ").strip() or "http://localhost:11434/v1"
    
    client = OpenAI(
        base_url=base_url,
        api_key="fake_key"
    )
    
    # Auto-detect model
    try:
        models = client.models.list()
        model_name = models.data[0].id if models.data else "llama3"
        print(f"\n✓ Auto-detected model: {model_name}")
    except:
        model_name = input("Model name [llama3]: ").strip() or "llama3"
        print(f"\n✓ Using model: {model_name}")
    
    # Configuration
    namespace = input("\nDefault namespace [default]: ").strip() or "default"
    registry = input("Azure Container Registry (optional): ").strip() or None
    auto_confirm = input("Auto-confirm actions? (y/n) [n]: ").strip().lower() == 'y'
    
    # Initialize agent
    agent = DynamicAKSAgent(
        llm_client=client,
        model_name=model_name,
        default_namespace=namespace,
        default_registry=registry,
        auto_confirm=auto_confirm
    )
    
    print("\n✓ Agent initialized")
    print("\nCommands:")
    print("  - Type your deployment command in natural language")
    print("  - Type 'help' to see available actions")
    print("  - Type 'exit' to quit\n")
    
    while True:
        try:
            user_input = input(">>> ").strip()
            
            if not user_input:
                continue
            
            if user_input.lower() in ['exit', 'quit', 'q']:
                print("Goodbye!")
                break
            
            if user_input.lower() == 'help':
                print("\nAvailable Actions:")
                actions = agent.get_available_actions()
                for action_id, description in actions.items():
                    print(f"  - {description}")
                print()
                continue
            
            # Process command
            result = agent.process_command(user_input)
            
            # Handle confirmation
            if result.get('requires_confirmation'):
                print_result(result)
                confirm = input("Execute this action? (y/n): ").strip().lower()
                if confirm == 'y':
                    result = agent.execute_action(result['intent'], result['parameters'])
                    print_result(result)
                else:
                    print("Action cancelled.\n")
            else:
                print_result(result)
        
        except KeyboardInterrupt:
            print("\n\nInterrupted. Type 'exit' to quit.\n")
        except Exception as e:
            print(f"\nError: {e}\n")
            import traceback
            traceback.print_exc()


if __name__ == "__main__":
    main()
