"""
Templates commands for NWO CLI
"""

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

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

console = Console()


@click.group(name="templates")
def templates():
    """
    Manage reusable task templates.
    
    Examples:
        nwo templates create "morning_routine" --tasks '[{"action": "check_sensors"}]'
    """
    pass


@templates.command(name="create")
@click.argument("name")
@click.option("--tasks", "-t", required=True, help="JSON array of tasks")
@click.option("--schedule", "-s", help="Cron schedule (optional)")
@click.option("--json-output", "-j", is_flag=True, help="Output raw JSON")
def create_template(name, tasks, schedule, json_output):
    """
    Create a reusable task template.
    
    NAME: Template name
    """
    try:
        client = NWOClient()
        
        try:
            tasks_list = json.loads(tasks)
        except json.JSONDecodeError:
            console.print("[red]Error:[/red] Tasks must be valid JSON array")
            return
        
        with console.status(f"[bold green]Creating template '{name}'..."):
            result = client.create_template(name, tasks_list, schedule)
        
        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 template')}")
            return
        
        console.print(Panel(
            f"[bold green]✓ Template Created[/bold green]\n\n"
            f"[cyan]Template ID:[/cyan] {result.get('template_id', 'N/A')}\n"
            f"[cyan]Name:[/cyan] {result.get('name', name)}\n"
            f"[cyan]Tasks:[/cyan] {result.get('task_count', 0)}\n"
            f"[cyan]Schedule:[/cyan] {result.get('schedule', 'None (manual)')}",
            title="Task Template",
            border_style="green"
        ))
        
    except NWOAPIError as e:
        handle_error(e)


@templates.command(name="list")
def list_templates():
    """List all templates."""
    console.print("[yellow]Template listing requires API v2.1+[/yellow]")


@templates.command(name="example")
def show_example():
    """Show example template format."""
    example = {
        "name": "morning_routine",
        "tasks": [
            {"action": "check_sensors"},
            {"action": "patrol", "area": "warehouse"},
            {"action": "report_status"}
        ],
        "schedule": "0 8 * * *"
    }
    
    console.print(Panel(
        json.dumps(example, indent=2),
        title="Example Template",
        border_style="cyan"
    ))
    
    console.print("\n[dim]Create with:[/dim]")
    console.print(f'  nwo templates create "morning_routine" --tasks \'{json.dumps(example["tasks"])}\' --schedule "0 8 * * *"')
