"""
Tasks 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="tasks")
def tasks():
    """
    Manage task plans and progress tracking.
    
    Examples:
        nwo tasks plan "clean warehouse"     # Create task plan
        nwo tasks progress <task_id>         # Subscribe to progress updates
    """
    pass


@tasks.command(name="plan")
@click.argument("instruction")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def create_plan(instruction, json_output):
    """
    Create a multi-step task plan.
    
    INSTRUCTION: High-level goal (e.g., "clean the warehouse")
    """
    try:
        client = NWOClient()
        
        with console.status("[bold green]Creating task plan..."):
            result = client.create_task_plan(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', 'Failed to create plan')}")
            return
        
        subtasks = result.get("subtasks", [])
        
        console.print(Panel(
            f"[bold green]✓ Task Plan Created[/bold green]\n\n"
            f"[cyan]Plan ID:[/cyan] {result.get('plan_id', 'N/A')}\n"
            f"[cyan]Total Steps:[/cyan] {len(subtasks)}",
            title="Task Plan",
            border_style="green"
        ))
        
        if subtasks:
            console.print("\n[bold]Subtasks:[/bold]")
            table = Table(show_header=True, header_style="bold magenta")
            table.add_column("Step")
            table.add_column("Instruction")
            table.add_column("Dependencies")
            
            for task in subtasks:
                deps = task.get("dependencies", [])
                deps_str = ", ".join(map(str, deps)) if deps else "None"
                table.add_row(
                    str(task.get("step", "?")),
                    task.get("instruction", "N/A"),
                    deps_str
                )
            
            console.print(table)
        
    except NWOAPIError as e:
        handle_error(e)


@tasks.command(name="progress")
@click.argument("task_id")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def subscribe_progress(task_id, json_output):
    """
    Subscribe to task progress updates.
    
    TASK_ID: The task to monitor
    """
    try:
        client = NWOClient()
        
        with console.status("[bold green]Subscribing to progress updates..."):
            result = client.subscribe_progress(task_id)
        
        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', 'Failed to subscribe')}")
            return
        
        console.print(Panel(
            f"[bold green]✓ Progress Subscription Active[/bold green]\n\n"
            f"[cyan]Subscription ID:[/cyan] {result.get('subscription_id', 'N/A')}\n"
            f"[cyan]Task ID:[/cyan] {result.get('task_id', 'N/A')}\n"
            f"[cyan]Milestone Interval:[/cyan] {result.get('milestone_interval', 'N/A')}%",
            title="Progress Subscription",
            border_style="green"
        ))
        
        if result.get("websocket_url"):
            console.print(f"\n[dim]WebSocket: {result.get('websocket_url')}[/dim]")
        
    except NWOAPIError as e:
        handle_error(e)
