"""Command-line interface for wideholy.

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

Usage::

    wideholy votd                                  # Verse of the day (Bible)
    wideholy votd --religion quran                 # Verse of the day (Quran)
    wideholy random                                # Random verse from any religion
    wideholy random --religion torah               # Random Torah verse
    wideholy compare genesis.1.1 john.1.1          # Compare two Bible verses
    wideholy compare bible:genesis.1.1 quran:al-fatihah.1  # Cross-religion
    wideholy search love                           # Search suggestions
    wideholy topic creation                        # Verses about creation
    wideholy cross-religion prayer                 # Cross-religion comparison
    wideholy calendar                              # All religious events
    wideholy calendar --religion torah --month 3   # Torah events in March
    wideholy commentary quran:al-fatihah.1         # Commentary for a verse
"""

from __future__ import annotations

import json

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

app = typer.Typer(
    name="wideholy",
    help="Cross-religion scripture search, comparison, and verse of the day.",
    no_args_is_help=True,
)
console = Console()


def _client() -> "WideHoly":  # type: ignore[name-defined]  # noqa: F821, UP037
    from wideholy.api import WideHoly

    return WideHoly()


def _print_verse(data: dict[str, object]) -> None:
    """Pretty-print a single verse."""
    table = Table(show_header=False, box=None, padding=(0, 2))
    table.add_column("Key", style="cyan", no_wrap=True)
    table.add_column("Value")

    table.add_row("Religion", str(data.get("religion", "")))
    table.add_row("Reference", str(data.get("reference", "")))
    table.add_row("Text", str(data.get("text", "")))
    table.add_row("Translation", str(data.get("translation", "")))
    if data.get("date"):
        table.add_row("Date", str(data["date"]))
    console.print(table)


@app.command()
def votd(
    religion: str = typer.Option("bible", help="Religion key (bible, quran, torah, gita, sutra)"),
    date: str | None = typer.Option(None, help="Date in YYYY-MM-DD format"),
) -> None:
    """Get the verse of the day."""
    with _client() as c:
        data = c.verse_of_the_day(religion=religion, date=date)
    _print_verse(data)


@app.command()
def random(
    religion: str | None = typer.Option(None, help="Religion key (default: random)"),
) -> None:
    """Get a random verse from any religion."""
    with _client() as c:
        data = c.random_verse(religion=religion)
    _print_verse(data)


@app.command()
def compare(
    ref_a: str = typer.Argument(help="First verse reference"),
    ref_b: str = typer.Argument(help="Second verse reference"),
) -> None:
    """Compare two verses side-by-side."""
    with _client() as c:
        data = c.compare(ref_a, ref_b)

    console.print("[bold]Verse A[/]")
    _print_verse(data["verse_a"])
    console.print()
    console.print("[bold]Verse B[/]")
    _print_verse(data["verse_b"])
    console.print()
    same = data.get("same_religion", False)
    label = "Same religion" if same else "Cross-religion"
    console.print(f"[dim]{label} comparison[/]")


@app.command()
def search(
    query: str = typer.Argument(help="Search query"),
    religion: str | None = typer.Option(None, help="Filter to specific religion"),
) -> None:
    """Search for topics, people, and glossary terms across religions."""
    with _client() as c:
        data = c.search_suggest(query=query, religion=religion)

    suggestions = data.get("suggestions", [])
    if not suggestions:
        console.print("[dim]No suggestions found.[/]")
        return

    table = Table(title=f"Search: {query}")
    table.add_column("Text", style="bold")
    table.add_column("Type", style="cyan")
    table.add_column("Religion", style="green")

    for s in suggestions:
        table.add_row(str(s.get("text", "")), str(s.get("type", "")), str(s.get("religion", "")))
    console.print(table)


@app.command()
def topic(
    slug: str = typer.Argument(help="Topic slug (e.g. love, creation, prayer)"),
) -> None:
    """Get verses for a topic across all religions."""
    with _client() as c:
        data = c.topic_verses(slug)

    console.print(f"[bold]Topic:[/] {data.get('topic', slug)}")
    console.print(f"[dim]Found in: {', '.join(data.get('religions_found', []))}[/]")
    console.print()

    verses = data.get("verses", {})
    for rel, info in verses.items():
        name = info.get("topic_name", "")
        count = info.get("verse_count", 0)
        console.print(f"  [cyan]{rel}[/]: {name} ({count} verses)")


@app.command(name="cross-religion")
def cross_religion(
    topic_key: str = typer.Argument(help="Topic key (e.g. creation, prayer, love)"),
) -> None:
    """Get cross-religion comparison for a spiritual theme."""
    with _client() as c:
        data = c.cross_religion(topic_key)

    console.print(f"[bold]{data.get('title', topic_key)}[/]")
    if data.get("summary"):
        console.print(f"[dim]{data['summary']}[/]")
    console.print()

    religions = data.get("religions", {})
    for rel, info in religions.items():
        console.print(f"  [cyan]{rel}[/]: {info.get('summary', '')}")
        for v in info.get("verses", []):
            console.print(f"    [{v.get('reference', '')}] {v.get('text', '')[:100]}")
        console.print()


@app.command()
def calendar(
    religion: str | None = typer.Option(None, help="Filter by religion key"),
    year: int | None = typer.Option(None, help="Year (default: 2026)"),
    month: int | None = typer.Option(None, help="Month number (1-12)"),
) -> None:
    """Get religious calendar events."""
    with _client() as c:
        data = c.calendar(religion=religion, year=year, month=month)

    events = data.get("events", [])
    if not events:
        console.print("[dim]No events found.[/]")
        return

    table = Table(title="Religious Calendar")
    table.add_column("Date", style="cyan", no_wrap=True)
    table.add_column("Religion", style="green")
    table.add_column("Event", style="bold")

    for e in events:
        table.add_row(str(e.get("date", "")), str(e.get("religion", "")), str(e.get("name", "")))
    console.print(table)


@app.command()
def commentary(
    verse_ref: str = typer.Argument(help="Verse reference (e.g. quran:al-fatihah.1)"),
) -> None:
    """Get commentary for a verse."""
    with _client() as c:
        data = c.commentary(verse_ref)

    entries = data.get("commentaries", [])
    if not entries:
        console.print(f"[dim]No commentaries found for {verse_ref}.[/]")
        return

    ref = data.get("verse_ref", verse_ref)
    rel = data.get("religion", "")
    console.print(f"[bold]Commentary for[/] {ref} [dim]({rel})[/]")
    console.print()

    for entry in entries:
        console.print(f"  [cyan]{entry.get('source', '')}[/] — {entry.get('author', '')}")
        console.print(f"  {entry.get('text', '')[:300]}")
        console.print()


@app.command(name="json")
def json_output(
    endpoint: str = typer.Argument(help="Endpoint path (e.g. verse-of-the-day, random, calendar)"),
) -> None:
    """Raw JSON output for any hub endpoint (for scripting)."""
    with _client() as c:
        data = c._get(f"{endpoint}/")
    console.print_json(json.dumps(data))
