"""CLI TecJustica — Cliente MCP para terminal."""

from __future__ import annotations

from importlib.metadata import PackageNotFoundError, version

import typer
from rich.console import Console

from tecjustica_cli.client import AuthError, MCPError
from tecjustica_cli.commands.analise import register_analise
from tecjustica_cli.commands.auth import app as auth_app
from tecjustica_cli.commands.busca import register_busca
from tecjustica_cli.commands.estatisticas import register_estatisticas
from tecjustica_cli.commands.navegacao import register_navegacao
from tecjustica_cli.commands.utilidades import register_utilidades

console = Console()

app = typer.Typer(
    name="tecjustica",
    help="CLI para consulta de processos judiciais via MCP (TecJustica).",
    no_args_is_help=True,
    rich_markup_mode="rich",
)


def _version_callback(value: bool) -> None:
    if value:
        try:
            v = version("tecjustica-mcp")
        except PackageNotFoundError:
            v = "dev"
        console.print(f"tecjustica {v}")
        raise typer.Exit()


@app.callback()
def main(
    ctx: typer.Context,
    version: bool | None = typer.Option(
        None,
        "--version",
        "-v",
        callback=_version_callback,
        is_eager=True,
        help="Mostrar versão e sair.",
    ),
    json_output: bool = typer.Option(
        False,
        "--json",
        "-j",
        help="Saída em JSON puro (para scripting).",
    ),
) -> None:
    """CLI TecJustica — consulta de processos judiciais."""
    ctx.ensure_object(dict)
    ctx.obj["json"] = json_output


# Registrar subcomandos
app.add_typer(auth_app, name="auth")
register_navegacao(app)
register_busca(app)
register_analise(app)
register_estatisticas(app)
register_utilidades(app)


def _error_handler() -> None:
    """Wrapper para tratar erros globalmente."""
    try:
        app()
    except AuthError as e:
        console.print(f"[red]Erro de autenticação: {e}[/red]")
        raise SystemExit(1) from None
    except MCPError as e:
        console.print(f"[red]Erro MCP ({e.code}): {e.message}[/red]")
        raise SystemExit(1) from None
    except Exception as e:
        console.print(f"[red]Erro: {e}[/red]")
        raise SystemExit(1) from None


if __name__ == "__main__":
    _error_handler()
