"""Command-line interface for widetorah.

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

Usage::

    widetorah verse genesis 1 1          # Get Genesis 1:1
    widetorah parashah bereshit          # Get Bereshit parashah details
    widetorah daf berakhot 2 a           # Get Talmud Berakhot 2a
    widetorah search "covenant"          # Search Torah verses
    widetorah books                      # List Tanakh books
    widetorah tractates                  # List Talmud tractates
    widetorah holidays                   # List Jewish holidays
    widetorah figures                    # List biblical figures
"""

from __future__ import annotations

import json

import typer
from rich.console import Console
from rich.table import Table

app = typer.Typer(
    name="widetorah",
    help="Python SDK for WideTorah — Torah, Talmud, Rashi commentary, parashot, Jewish holidays.",
    no_args_is_help=True,
)
console = Console()


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 verse(
    book: str = typer.Argument(help="Book slug (e.g. genesis, exodus)"),
    chapter: int = typer.Argument(help="Chapter number"),
    verse_num: int = typer.Argument(help="Verse number"),
    translation: str = typer.Option("jps-1917", "--translation", "-t", help="Translation code"),
) -> None:
    """Get a specific Torah verse (e.g. widetorah verse genesis 1 1)."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.get_verse(book, chapter, verse_num, translation=translation)

    results = data.get("results", [data] if "id" in data else [])
    if not results:
        console.print("[red]Verse not found.[/red]")
        raise typer.Exit(1)

    v = results[0] if isinstance(results, list) else data
    ref = v.get("reference", f"{book} {chapter}:{verse_num}")
    console.print(f"\n[bold cyan]{ref}[/bold cyan]")
    if v.get("text_hebrew"):
        console.print(f"[dim]{v['text_hebrew']}[/dim]")
    if v.get("text"):
        console.print(f"{v['text']}\n")


@app.command()
def parashah(
    slug: str = typer.Argument(help="Parashah slug (e.g. bereshit, noach)"),
) -> None:
    """Get weekly Torah portion details."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.get_parashah(slug)

    console.print(f"\n[bold cyan]{data.get('name', slug)}[/bold cyan]")
    if data.get("hebrew_name"):
        console.print(f"Hebrew: {data['hebrew_name']}")
    if data.get("reference"):
        console.print(f"Reference: {data['reference']}")
    if data.get("description"):
        console.print(f"\n{data['description']}\n")


@app.command()
def daf(
    tractate: str = typer.Argument(help="Tractate slug (e.g. berakhot, shabbat)"),
    number: int = typer.Argument(help="Daf (folio) number"),
    side: str = typer.Argument("a", help="Page side: a (recto) or b (verso)"),
) -> None:
    """Get a Talmud daf page (e.g. widetorah daf berakhot 2 a)."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.get_talmud_daf(tractate, number, side=side)

    results = data.get("results", [data] if "id" in data else [])
    if not results:
        console.print("[red]Daf not found.[/red]")
        raise typer.Exit(1)

    d = results[0] if isinstance(results, list) else data
    console.print(f"\n[bold cyan]{tractate.title()} {number}{side}[/bold cyan]")
    if d.get("text_hebrew"):
        console.print(f"\n[dim]{d['text_hebrew'][:200]}...[/dim]")
    if d.get("text_english"):
        console.print(f"\n{d['text_english'][:500]}...\n")


@app.command()
def search(
    query: str = typer.Argument(help="Search query (e.g. 'covenant', 'blessing')"),
    limit: int = typer.Option(10, "--limit", "-n", help="Max results"),
) -> None:
    """Search Torah verses by keyword."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.search(query, limit=limit)

    results = data.get("results", [])
    if not results:
        console.print("[yellow]No results found.[/yellow]")
        raise typer.Exit(0)

    table = Table(title=f"Search: '{query}'")
    table.add_column("Reference", style="cyan", no_wrap=True)
    table.add_column("Text", max_width=80)

    for v in results:
        ref = v.get("reference", "")
        text = (v.get("text", "") or "")[:120]
        table.add_row(ref, text)

    console.print(table)


@app.command()
def books(
    section: str | None = typer.Option(
        None, "--section", "-s", help="Filter: torah/neviim/ketuvim"
    ),
) -> None:
    """List all 24 books of the Tanakh."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.list_books(section=section)

    results = data.get("results", [])
    table = Table(title="Tanakh Books")
    table.add_column("#", style="dim", justify="right")
    table.add_column("Name", style="cyan")
    table.add_column("Hebrew", style="green")
    table.add_column("Section")
    table.add_column("Chapters", justify="right")
    table.add_column("Verses", justify="right")

    for b in results:
        table.add_row(
            str(b.get("number", "")),
            b.get("name", ""),
            b.get("hebrew_name", ""),
            b.get("section", ""),
            str(b.get("chapter_count", "")),
            str(b.get("verse_count", "")),
        )

    console.print(table)


@app.command()
def tractates(
    seder: str | None = typer.Option(None, "--seder", help="Filter by seder name"),
) -> None:
    """List Talmud tractates."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.list_tractates(seder=seder)

    results = data.get("results", [])
    table = Table(title="Talmud Tractates")
    table.add_column("Name", style="cyan")
    table.add_column("Hebrew", style="green")
    table.add_column("Seder")
    table.add_column("Daf Count", justify="right")

    for t in results:
        table.add_row(
            t.get("name", ""),
            t.get("hebrew_name", ""),
            t.get("seder", ""),
            str(t.get("daf_count", "")),
        )

    console.print(table)


@app.command()
def holidays(
    category: str | None = typer.Option(None, "--category", "-c", help="Filter by category"),
) -> None:
    """List Jewish holidays."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.list_holidays(category=category)

    results = data.get("results", [])
    table = Table(title="Jewish Holidays")
    table.add_column("Name", style="cyan")
    table.add_column("Hebrew", style="green")
    table.add_column("Date")
    table.add_column("Category")

    for h in results:
        table.add_row(
            h.get("name", ""),
            h.get("hebrew_name", ""),
            h.get("hebrew_date", ""),
            h.get("category", ""),
        )

    console.print(table)


@app.command()
def figures(
    era: str | None = typer.Option(None, "--era", help="Filter by era"),
) -> None:
    """List biblical figures (patriarchs, prophets, kings)."""
    from widetorah import WideTorah

    with WideTorah() as client:
        data = client.list_figures(era=era)

    results = data.get("results", [])
    table = Table(title="Biblical Figures")
    table.add_column("Name", style="cyan")
    table.add_column("Hebrew", style="green")
    table.add_column("Era")
    table.add_column("Prophet?", justify="center")

    for f in results:
        table.add_row(
            f.get("name", ""),
            f.get("hebrew_name", ""),
            f.get("era", ""),
            "Yes" if f.get("is_prophet") else "",
        )

    console.print(table)
