"""Skills commands — interactive knowledge base for AI agents."""

from __future__ import annotations

import json

from rich.table import Table
import typer

from turumba_cli.output import console, error, info
from turumba_cli.skills.registry import SkillTopic, get_topic, list_topics, search

app = typer.Typer(name="skills", help="Interactive skill topics for AI agent integration.")


def _render_params_table(topic: SkillTopic) -> None:
    """Render the create parameters table and notes sections."""
    if topic.create_params:
        param_table = Table(title="Create Parameters", show_lines=False)
        param_table.add_column("Parameter", style="cyan")
        param_table.add_column("Type", style="yellow")
        param_table.add_column("Req?", style="bold")
        param_table.add_column("Description")
        param_table.add_column("Default/Values", style="dim")

        for p in topic.create_params:
            req = "YES" if p.required else "no"
            extra = ""
            if p.enum_values:
                extra = ", ".join(p.enum_values)
            elif p.default:
                extra = p.default
            if p.condition:
                extra += f" ({p.condition})" if extra else p.condition
            param_table.add_row(p.name, p.type, req, p.description, extra)

        console.print(param_table)
        console.print()

    if topic.notes:
        console.print("[bold]Notes:[/bold]")
        for note in topic.notes:
            console.print(f"  \u2022 {note}")
        console.print()


def _render_topic_table(topic: SkillTopic) -> None:
    """Render a topic's details as formatted Rich output."""
    console.print(f"\n[bold]{topic.name}[/bold] — {topic.summary}\n")

    if topic.commands:
        console.print("[bold]Commands:[/bold]")
        for cmd in topic.commands:
            console.print(f"  {cmd}")
        console.print()

    _render_params_table(topic)

    if topic.examples:
        console.print("[bold]Examples:[/bold]")
        for ex in topic.examples:
            console.print(f"  [dim]$[/dim] {ex}")
        console.print()

    if topic.workflows:
        console.print("[bold]Workflows:[/bold]")
        for wf in topic.workflows:
            console.print(f"  [bold]{wf['name']}[/bold]")
            for i, step in enumerate(wf["steps"], 1):
                console.print(f"    {i}. {step}")
        console.print()

    if topic.related:
        console.print(f"[dim]Related: {', '.join(topic.related)}[/dim]\n")


@app.command("list")
def list_skills(
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
) -> None:
    """List all available skill topics."""
    topics = list_topics()

    if output == "json":
        data = [{"name": t.name, "summary": t.summary, "related": t.related} for t in topics]
        console.print_json(json.dumps(data, default=str))
        return

    table = Table(title="Skill Topics", show_lines=False)
    table.add_column("Topic", style="cyan")
    table.add_column("Summary")
    table.add_column("Related")

    for topic in topics:
        table.add_row(topic.name, topic.summary, ", ".join(topic.related))

    console.print(table)


@app.command("show")
def show_skill(
    topic_name: str = typer.Argument(help="Topic name (e.g. auth, channels, sending)"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
) -> None:
    """Show details for a specific skill topic."""
    topic = get_topic(topic_name)
    if not topic:
        error(f"Unknown topic: {topic_name}")
        available = ", ".join(t.name for t in list_topics())
        info(f"Available topics: {available}")
        raise typer.Exit(1)

    if output == "json":
        data = {
            "name": topic.name,
            "summary": topic.summary,
            "commands": topic.commands,
            "create_params": [
                {
                    "name": p.name,
                    "type": p.type,
                    "required": p.required,
                    "description": p.description,
                    **({"default": p.default} if p.default else {}),
                    **({"enum_values": p.enum_values} if p.enum_values else {}),
                    **({"condition": p.condition} if p.condition else {}),
                }
                for p in topic.create_params
            ],
            "notes": topic.notes,
            "examples": topic.examples,
            "workflows": topic.workflows,
            "related": topic.related,
        }
        console.print_json(json.dumps(data, default=str))
        return

    _render_topic_table(topic)


@app.command("how-to")
def how_to(
    query: str = typer.Argument(help="Describe what you want to do"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
) -> None:
    """Find the most relevant skill topic and workflow for a query."""
    results = search(query)
    if not results:
        error("No matching topics found.")
        info("Try: turumba skills list")
        raise typer.Exit(1)

    top_topic, score = results[0]

    if output == "json":
        data = {
            "topic": top_topic.name,
            "summary": top_topic.summary,
            "score": score,
            "commands": top_topic.commands,
            "examples": top_topic.examples,
            "workflows": top_topic.workflows,
        }
        console.print_json(json.dumps(data, default=str))
        return

    console.print(f"\n[bold]Best match:[/bold] {top_topic.name} — {top_topic.summary}\n")

    if top_topic.workflows:
        for wf in top_topic.workflows:
            console.print(f"  [bold]{wf['name']}[/bold]")
            for i, step in enumerate(wf["steps"], 1):
                console.print(f"    {i}. {step}")
        console.print()
    elif top_topic.examples:
        console.print("[bold]Examples:[/bold]")
        for ex in top_topic.examples[:5]:
            console.print(f"  [dim]$[/dim] {ex}")
        console.print()

    if len(results) > 1:
        others = ", ".join(t.name for t, _ in results[1:4])
        console.print(f"[dim]Also related: {others}[/dim]\n")
