"""Command-line interface for WideSutra.

Requires the ``cli`` extra: ``pip install widesutra[cli]``

Usage::

    widesutra search "four noble truths"
    widesutra collection tipitaka
    widesutra book dhammapada
    widesutra figure siddhartha-gautama
    widesutra concept four-noble-truths
"""

from __future__ import annotations

import json

import typer
from rich.console import Console

from widesutra.client import WideSutra

app = typer.Typer(
    name="widesutra",
    help="WideSutra CLI — Buddhist scriptures, Tipitaka, Pali Canon, figures, concepts.",
    no_args_is_help=True,
)
console = Console()
err_console = Console(stderr=True)


def _print_json(data: dict) -> None:  # type: ignore[type-arg]
    """Pretty-print JSON response."""
    console.print_json(json.dumps(data, ensure_ascii=False, indent=2))


@app.command()
def search(
    query: str = typer.Argument(help="Search query (e.g. 'four noble truths')"),
    limit: int = typer.Option(10, "--limit", "-n", help="Max results"),
) -> None:
    """Search Buddhist scripture texts by keyword."""
    with WideSutra() as client:
        result = client.search(query, limit=limit)
    results = result.get("results", [])
    if results:
        for v in results:
            ref = v.get("reference", "")
            text = v.get("text", "")
            console.print(f"[bold]{ref}[/bold]")
            console.print(f"  {text[:120]}{'...' if len(text) > 120 else ''}")
            console.print()
    else:
        console.print("[yellow]No results found.[/yellow]")


@app.command()
def collection(
    slug: str = typer.Argument(help="Collection slug (e.g. tipitaka)"),
) -> None:
    """Get scripture collection details."""
    with WideSutra() as client:
        try:
            result = client.get_collection(slug)
        except Exception as e:
            err_console.print(f"[red]Error: {e}[/red]")
            raise typer.Exit(1) from None
    name = result.get("name", slug)
    tradition = result.get("tradition", "")
    text_count = result.get("text_count", 0)
    description = result.get("description", "")
    console.print(f"[bold]{name}[/bold] ({tradition})")
    console.print(f"Texts: {text_count}")
    if description:
        console.print(f"\n{description}")


@app.command()
def book(
    slug: str = typer.Argument(help="Book slug (e.g. dhammapada, heart-sutra)"),
) -> None:
    """Get book details."""
    with WideSutra() as client:
        try:
            result = client.get_book(slug)
        except Exception as e:
            err_console.print(f"[red]Error: {e}[/red]")
            raise typer.Exit(1) from None
    name = result.get("name", slug)
    pali = result.get("pali_name", "")
    chapters = result.get("chapter_count", 0)
    description = result.get("description", "")
    title_parts = [name]
    if pali:
        title_parts.append(f"({pali})")
    console.print(f"[bold]{' '.join(title_parts)}[/bold]")
    console.print(f"Chapters: {chapters}")
    if description:
        console.print(f"\n{description}")


@app.command()
def figure(
    slug: str = typer.Argument(help="Figure slug (e.g. siddhartha-gautama)"),
) -> None:
    """Get information about a Buddhist figure."""
    with WideSutra() as client:
        try:
            result = client.get_figure(slug)
        except Exception as e:
            err_console.print(f"[red]Error: {e}[/red]")
            raise typer.Exit(1) from None
    name = result.get("name", slug)
    title = result.get("title", "")
    tradition = result.get("tradition", "")
    description = result.get("description", "")
    header = f"[bold]{name}[/bold]"
    if title:
        header += f" — {title}"
    if tradition:
        header += f" ({tradition})"
    console.print(header)
    if description:
        console.print(f"\n{description}")


@app.command()
def concept(
    slug: str = typer.Argument(help="Concept slug (e.g. four-noble-truths)"),
) -> None:
    """Get information about a Buddhist concept."""
    with WideSutra() as client:
        try:
            result = client.get_concept(slug)
        except Exception as e:
            err_console.print(f"[red]Error: {e}[/red]")
            raise typer.Exit(1) from None
    name = result.get("name", slug)
    pali = result.get("pali_term", "")
    sanskrit = result.get("sanskrit_term", "")
    category = result.get("category", "")
    description = result.get("description", "")
    header = f"[bold]{name}[/bold]"
    terms = []
    if pali:
        terms.append(f"Pali: {pali}")
    if sanskrit:
        terms.append(f"Sanskrit: {sanskrit}")
    if terms:
        header += f" ({', '.join(terms)})"
    console.print(header)
    if category:
        console.print(f"Category: {category}")
    if description:
        console.print(f"\n{description}")


if __name__ == "__main__":
    app()
