"""Main Typer app + shared helpers."""

from __future__ import annotations

import json
from typing import Any

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

app = typer.Typer(
    name="appliku",
    help="CLI and SDK for the Appliku platform.",
    invoke_without_command=True,
)


@app.callback(invoke_without_command=True)
def main_callback(ctx: typer.Context) -> None:
    """Show help if no command is provided."""
    if ctx.invoked_subcommand is None:
        typer.echo(ctx.get_help())


def get_client() -> Any:
    """Construct SDK client, with a clear error if no token configured."""
    from appliku import Appliku
    from appliku._exceptions import AuthenticationError

    try:
        return Appliku()
    except AuthenticationError:
        typer.echo(
            "Error: Not authenticated. Run `appliku login` first or set APPLIKU_TOKEN.", err=True
        )
        raise typer.Exit(1) from None


def render_output(
    rows: list[dict[str, Any]], columns: list[str], output: str, title: str = ""
) -> None:
    """Dispatch to table or JSON output based on --output flag."""
    if output == "json":
        typer.echo(json.dumps(rows, indent=2, default=str))
    else:
        render_table(rows, columns, title)


def render_table(rows: list[dict[str, Any]], columns: list[str], title: str = "") -> None:
    """Render rows as a Rich table."""
    console = Console()
    table = Table(title=title, show_header=True)
    for col in columns:
        table.add_column(col.replace("_", " ").title())
    for row in rows:
        table.add_row(*[str(row.get(c, "")) for c in columns])
    console.print(table)


# Import and register sub-apps
from appliku.cli.apps import apps_app  # noqa: E402
from appliku.cli.auth import register_auth_commands  # noqa: E402
from appliku.cli.clusters import clusters_app  # noqa: E402
from appliku.cli.cron_jobs import crons_app  # noqa: E402
from appliku.cli.datastores import datastores_app  # noqa: E402
from appliku.cli.deployments import deployments_app  # noqa: E402
from appliku.cli.domains import domains_app  # noqa: E402
from appliku.cli.invites import invites_app  # noqa: E402
from appliku.cli.migrations import migrations_app  # noqa: E402
from appliku.cli.servers import servers_app  # noqa: E402
from appliku.cli.teams import teams_app  # noqa: E402
from appliku.cli.volumes import volumes_app  # noqa: E402

# Auth commands go on root
register_auth_commands(app)

# Resource commands are sub-apps
app.add_typer(teams_app, name="teams")
app.add_typer(apps_app, name="apps")
app.add_typer(deployments_app, name="deployments")
app.add_typer(datastores_app, name="datastores")
app.add_typer(domains_app, name="domains")
app.add_typer(volumes_app, name="volumes")
app.add_typer(crons_app, name="crons")
app.add_typer(clusters_app, name="clusters")
app.add_typer(servers_app, name="servers")
app.add_typer(invites_app, name="invites")
app.add_typer(migrations_app, name="migrations")


def main() -> None:
    app()
