"""
Models commands for NWO CLI
"""

import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
import json

from ..client import NWOClient, NWOAPIError
from ..utils import handle_error

console = Console()


@click.group(name="models")
def models():
    """
    Manage AI models and view routing decisions.
    
    Examples:
        nwo models list              # List all configured models
        nwo models route "read label"  # Preview routing for instruction
    """
    pass


@models.command(name="list")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def list_models(json_output):
    """List all configured AI models."""
    try:
        client = NWOClient()
        
        with console.status("[bold green]Fetching models..."):
            result = client.list_models()
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if not result.get("success"):
            console.print("[yellow]No models configured yet.[/yellow]")
            console.print("[dim]Add models in the Developer Dashboard: https://nwo.capital/webapp/api-key.php[/dim]")
            return
        
        model_list = result.get("models", [])
        
        console.print(Panel(
            f"[bold green]Total Models:[/bold green] {len(model_list)}",
            title="Configured Models",
            border_style="green"
        ))
        
        if model_list:
            table = Table(show_header=True, header_style="bold magenta")
            table.add_column("Status")
            table.add_column("Name")
            table.add_column("Provider")
            table.add_column("Priority")
            table.add_column("Success Rate")
            table.add_column("Avg Latency")
            
            for model in model_list:
                status = "✓" if model.get("is_active") else "✗"
                total = max(model.get("total_requests", 1), 1)
                success_rate = (model.get("successful_requests", 0) / total) * 100
                
                table.add_row(
                    f"[green]{status}[/green]" if model.get("is_active") else f"[red]{status}[/red]",
                    model.get("model_name", "Unknown"),
                    model.get("model_provider", "unknown").upper(),
                    str(model.get("priority", 0)),
                    f"{success_rate:.1f}%",
                    f"{model.get('avg_latency_ms', 0):.0f}ms"
                )
            
            console.print(table)
        
    except NWOAPIError as e:
        handle_error(e)


@models.command(name="route")
@click.argument("instruction")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def preview_route(instruction, json_output):
    """
    Preview which model would be selected for an instruction.
    
    INSTRUCTION: The task you want to route (e.g., "read the label")
    """
    try:
        client = NWOClient()
        
        with console.status("[bold green]Analyzing routing decision..."):
            result = client.preview_routing(instruction)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if not result.get("success"):
            console.print(f"[red]Error:[/red] {result.get('error', 'Unknown error')}")
            return
        
        preview = result.get("routing_preview", {})
        classification = preview.get("task_classification", {})
        selected = preview.get("selected_model", {})
        fallback = preview.get("fallback_model", {})
        
        console.print(Panel(
            f"[cyan]Instruction:[/cyan] {instruction}\n"
            f"[cyan]Task Type:[/cyan] {classification.get('task_type', 'general').upper()}\n"
            f"[cyan]Confidence:[/cyan] {classification.get('confidence', 0) * 100:.1f}%",
            title="Routing Preview",
            border_style="cyan"
        ))
        
        console.print("\n[bold green]Selected Model:[/bold green]")
        selected_table = Table(show_header=False, box=None)
        selected_table.add_row("ID:", selected.get("id", "N/A"))
        selected_table.add_row("Name:", selected.get("name", "Unknown"))
        selected_table.add_row("Provider:", selected.get("provider", "xiaomi").upper())
        selected_table.add_row("Routing Score:", f"{preview.get('routing_score', 0)}/100")
        console.print(selected_table)
        
        if fallback:
            console.print("\n[bold yellow]Fallback Model:[/bold yellow]")
            console.print(f"  {fallback.get('name', 'N/A')} ({fallback.get('id', 'N/A')})")
        
        console.print(f"\n[dim]Reason: {preview.get('reason', 'Default selection')}[/dim]")
        
        # Task scores
        scores = classification.get("all_scores", {})
        if scores:
            console.print("\n[bold]Task Type Scores:[/bold]")
            for task_type, score in sorted(scores.items(), key=lambda x: x[1], reverse=True):
                bar = "█" * int(score * 10) + "░" * (10 - int(score * 10))
                console.print(f"  {task_type:15} {bar} {score:.2f}")
        
    except NWOAPIError as e:
        handle_error(e)
