"""Main CLI entry point."""

import sys
from datetime import datetime, timezone

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

_UPDATE_CHECK_INTERVAL_HOURS = 24


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 = make_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})


def _check_for_update() -> None:
    """Print a one-line nudge if a newer version is available on PyPI.

    Checks at most once every 24 hours, caches the result in config.yaml,
    and silently swallows all exceptions.
    """
    try:
        if not sys.stderr.isatty():
            return

        config = load_config()

        last_check = config.get("last_version_check")
        if last_check:
            last_dt = datetime.fromisoformat(last_check)
            age_hours = (datetime.now(timezone.utc) - last_dt).total_seconds() / 3600
            if age_hours < _UPDATE_CHECK_INTERVAL_HOURS:
                return

        import httpx
        from packaging.version import Version

        resp = httpx.get("https://pypi.org/pypi/gjalla/json", timeout=2)
        resp.raise_for_status()
        latest_str = resp.json()["info"]["version"]

        save_config({
            "last_version_check": datetime.now(timezone.utc).isoformat(),
            "latest_pypi_version": latest_str,
        })

        if Version(latest_str) > Version(__version__):
            console = make_console(stderr=True)
            console.print(
                f"  [dim]Update available:[/dim] {__version__} → [bold]{latest_str}[/bold]"
                f" [dim]— run[/dim] [bold]pip install --upgrade gjalla[/bold]"
            )
    except Exception:  # noqa: BLE001
        pass


@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()
        _check_for_update()


@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)
main.add_command(show.show)


if __name__ == "__main__":
    main()
