"""Main CLI entry point."""

import sys

import click
from rich.console import Console

from . import __version__
from .commands import init, status, sync, auth, mcp, setup, check, attest, connect
from .config.settings import load_config, save_config
from .display.output import bridge_banner
from . import telemetry


def _show_beta_banner() -> None:
    """Show a beta notice once per version (only for pre-1.0 releases)."""
    if not sys.stderr.isatty():
        return

    version = __version__
    if not version.startswith("0."):
        return

    config = load_config()
    if config.get("last_seen_version") == version:
        return

    console = Console(stderr=True)
    bridge_banner(target=console)
    console.print(
        f"  [bold]gjalla {version}[/bold] [dim]· beta[/dim]  [blue]✦[/blue] [purple]✦[/purple]"
    )
    console.print()
    console.print("  [dim]Feedback welcome →[/dim] [cyan]hello@gjalla.io[/cyan]")
    console.print(
        "  [dim]Something break after upgrading? Re-run[/dim] [bold]gjalla setup[/bold]"
    )
    console.print()
    save_config({"last_seen_version": version})


@click.group()
@click.version_option(version=__version__, prog_name="gjalla")
@click.pass_context
def main(ctx):
    """Gjalla — architecture guardrails for AI coding agents."""
    ctx.ensure_object(dict)
    if not ctx.resilient_parsing:
        telemetry.check_consent()
        _show_beta_banner()


@main.result_callback()
@click.pass_context
def _track(ctx, *_args, **_kwargs):
    telemetry.track(ctx.info_name if ctx.invoked_subcommand is None else ctx.invoked_subcommand)


main.add_command(init.init)
main.add_command(status.status)
main.add_command(sync.sync)
main.add_command(auth.auth)
main.add_command(mcp.mcp)
main.add_command(setup.setup)
main.add_command(check.check)
main.add_command(attest.attest)
main.add_command(connect.connect)


if __name__ == "__main__":
    main()
