"""
Module: main
Description: Main CLI entry point for Huitzo

Implements:
    - docs/cli/reference.md
    - docs/guides/developer-environment.md#cli-interface

See Also:
    - docs/architecture/overview.md (for platform architecture)
"""

from __future__ import annotations

import sys

import typer
from rich.console import Console

from huitzo_cli.commands.add_command import add_command
from huitzo_cli.commands.auth import login, logout
from huitzo_cli.commands.build import build
from huitzo_cli.commands.config_cmd import config_app
from huitzo_cli.commands.dashboard import dashboard_app
from huitzo_cli.commands.dev import dev
from huitzo_cli.commands.init import init
from huitzo_cli.commands.registry import install, list_packs, publish, run
from huitzo_cli.commands.secrets import secrets_app
from huitzo_cli.commands.status import status
from huitzo_cli.commands.test import test
from huitzo_cli.commands.validate import validate
from huitzo_cli.config import ConfigManager
from huitzo_cli.telemetry import prompt_telemetry_opt_in
from huitzo_cli.version import get_version

console = Console()
app = typer.Typer(help="Huitzo CLI for developing Intelligence Packs")


@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context,
    version: bool = typer.Option(False, "--version", help="Show version and exit"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose output"),
    quiet: bool = typer.Option(False, "--quiet", "-q", help="Suppress output"),
    config: str | None = typer.Option(None, "--config", help="Path to config file"),
) -> None:
    """Huitzo CLI for developing Intelligence Packs."""
    if version:
        console.print(f"huitzo-cli {get_version()}")
        raise typer.Exit(0)

    # Store options in context for subcommands
    ctx.obj = {
        "verbose": verbose,
        "quiet": quiet,
        "config": config,
    }

    # Opt-in telemetry prompt on first run
    if ctx.invoked_subcommand is not None:
        try:
            cfg = ConfigManager()
            prompt_telemetry_opt_in(cfg)
        except Exception:
            pass  # Never block CLI on telemetry issues

    if ctx.invoked_subcommand is None and not version:
        console.print(ctx.get_help())


# Top-level shortcuts
app.command("login")(login)
app.command("logout")(logout)
app.command("run")(run)
app.command("status")(status)

# Pack subcommand group
pack_app = typer.Typer(help="Pack operations")
pack_app.command("new")(init)
pack_app.command("validate")(validate)
pack_app.command("test")(test)
pack_app.command("build")(build)
pack_app.command("dev")(dev)
pack_app.command("publish")(publish)
pack_app.command("install")(install)
pack_app.command("list")(list_packs)
pack_app.command("run")(run)
pack_app.command("add-command")(add_command)

# Register command groups
app.add_typer(pack_app, name="pack", help="Pack operations")
app.add_typer(config_app, name="config", help="Manage configuration")
app.add_typer(secrets_app, name="secrets", help="Manage secrets")
app.add_typer(dashboard_app, name="dashboard", help="Dashboard operations")


def _safe_main() -> None:
    """Run the CLI app with global exception handling to prevent traceback leaks."""
    try:
        app()
    except KeyboardInterrupt:
        console.print("\nInterrupted.")
        sys.exit(130)
    except SystemExit:
        raise
    except Exception:
        console.print("[red]An unexpected error occurred. Please report this issue.[/red]")
        sys.exit(1)


if __name__ == "__main__":
    _safe_main()
