"""appxen status — connectivity and auth check."""

from __future__ import annotations

import typer

from appxen_cli.display import console, error


def status(
    json_output: bool = typer.Option(False, "--json", help="Output raw JSON"),
) -> None:
    """Check connectivity and authentication."""
    from appxen_cli.main import get_client
    from appxen_cli.display import print_json

    try:
        client = get_client()
    except typer.Exit:
        raise

    try:
        health = client.health()
    except Exception as e:
        error(f"Cannot reach gateway: {e}")
        raise typer.Exit(1)

    try:
        rag_stats = client.stats()
    except Exception:
        rag_stats = None

    if json_output:
        print_json({"health": health, "rag_stats": rag_stats})
        return

    from appxen_cli import __version__

    console.print(f"[bold]CLI:[/bold]       {__version__}")
    console.print(f"[bold]Endpoint:[/bold]  {client.endpoint}")
    console.print(f"[bold]Service:[/bold]   {health.get('service', '?')}")
    console.print(f"[bold]Gateway:[/bold]   {health.get('version', '?')}")
    console.print(f"[bold]Status:[/bold]    [green]Connected[/green]")
    if rag_stats:
        console.print(
            f"[bold]RAG:[/bold]       {rag_stats.get('source_count', 0)} sources, "
            f"{rag_stats.get('chunk_count', 0)} chunks"
        )

    # Check for updates (non-blocking, errors silently ignored)
    from appxen_cli.version_check import is_update_available
    from appxen_cli import __version__

    available, latest = is_update_available()
    if available:
        console.print()
        console.print(
            f"[yellow]Update available:[/yellow] {__version__} → {latest}"
        )
        console.print("Run [bold]appxen update[/bold] to upgrade.")
