"""AppXen CLI — main entry point."""

from __future__ import annotations

import typer

from appxen_cli import __version__
from appxen_cli.client import AppXenClient
from appxen_cli.config import load_profile
from appxen_cli.display import error

app = typer.Typer(
    name="appxen",
    help="AppXen CLI — manage your MCP Gateway, RAG Engine, and Agent Orchestrator.",
    no_args_is_help=True,
)

# Global state
_profile_name: str = "default"


def _version_callback(value: bool) -> None:
    if value:
        typer.echo(f"appxen {__version__}")
        raise typer.Exit()


@app.callback()
def main(
    profile: str = typer.Option("default", "--profile", "-p", help="Config profile"),
    version: bool = typer.Option(False, "--version", "-v", callback=_version_callback, is_eager=True),
) -> None:
    """AppXen CLI."""
    global _profile_name
    _profile_name = profile


def get_client() -> AppXenClient:
    """Get an authenticated client from the active profile."""
    prof = load_profile(_profile_name)
    if prof is None:
        error("Not logged in. Run [bold]appxen login[/bold] first.")
        raise typer.Exit(1)
    return AppXenClient(api_key=prof.api_key, endpoint=prof.endpoint)


# Register commands
from appxen_cli.commands.login import login  # noqa: E402
from appxen_cli.commands.status import status  # noqa: E402
from appxen_cli.commands.sources import app as sources_app  # noqa: E402
from appxen_cli.commands.stats import stats  # noqa: E402
from appxen_cli.commands.search import search  # noqa: E402
from appxen_cli.commands.ingest import ingest  # noqa: E402
from appxen_cli.commands.workflow import app as workflow_app  # noqa: E402
from appxen_cli.commands.update import update  # noqa: E402

app.command()(login)
app.command()(status)
app.add_typer(sources_app, name="sources")
app.command()(stats)
app.command()(search)
app.command()(ingest)
app.command()(update)
app.add_typer(workflow_app, name="workflow")
