"""
Learning commands for NWO CLI
"""

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

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

console = Console()


@click.group(name="learning")
def learning():
    """
    Access the learning system and few-shot learning.
    
    Examples:
        nwo learning params --task pick_object --object glass
    """
    pass


@learning.command(name="params")
@click.option("--task", "-t", required=True, 
              type=click.Choice(["pick_object", "place_object", "navigate", "inspect", "general"]),
              help="Task type")
@click.option("--object", "object_type", 
              type=click.Choice(["", "glass", "metal", "plastic", "cardboard", "ceramic", "wood"]),
              help="Object type")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def get_params(task, object_type, json_output):
    """Get learned parameters for a task."""
    try:
        client = NWOClient()
        
        with console.status(f"[bold green]Getting learned parameters..."):
            result = client.get_learned_params(task, object_type)
        
        if json_output:
            console.print(json.dumps(result, indent=2))
            return
        
        if not result.get("success"):
            console.print(f"[yellow]No learned parameters found for '{task}'.[/yellow]")
            return
        
        console.print(Panel(
            f"[bold cyan]Task:[/bold cyan] {task}\n"
            f"[cyan]Object:[/cyan] {object_type or 'General'}\n"
            f"[cyan]Success Rate:[/cyan] {result.get('success_rate', 'N/A')}\n"
            f"[cyan]Attempts:[/cyan] {result.get('total_attempts', 0)}",
            title="Learned Parameters",
            border_style="cyan"
        ))
        
        params = result.get("parameters", {})
        if params:
            table = Table(show_header=True, header_style="bold magenta")
            table.add_column("Parameter")
            table.add_column("Value")
            for key, value in params.items():
                table.add_row(key, str(value))
            console.print(table)
        
    except NWOAPIError as e:
        handle_error(e)


@learning.command(name="record")
@click.option("--task", "-t", required=True, help="Task type")
@click.option("--object", "object_type", help="Object type")
@click.option("--success/--failure", required=True, help="Whether the task succeeded")
@click.option("--error", help="Error type if failed")
def record_outcome(task, object_type, success, error):
    """Record task outcome for learning."""
    console.print("[yellow]Recording outcomes via CLI is coming in v2.1[/yellow]")
    console.print("[dim]Use the API directly or Developer Dashboard for now.[/dim]")
