from __future__ import annotations

import shutil
import subprocess
from typing import Annotated

import typer

from cli_demo import PACKAGE_NAME, __version__

app = typer.Typer(
    help="A publishable CLI demo built with Typer.",
    no_args_is_help=True,
    add_completion=False,
)


@app.command()
def hello(
    name: Annotated[
        str,
        typer.Argument(help="Name to greet."),
    ] = "World",
) -> None:
    """Print a simple greeting."""

    typer.echo(f"Hello, {name}!")


@app.command()
def version() -> None:
    """Show the CLI version."""

    typer.echo(f"cli {__version__}")


@app.command()
def update(
    dry_run: Annotated[
        bool,
        typer.Option(
            "--dry-run",
            "-n",
            help="Show the selected update command without running it.",
        ),
    ] = False,
) -> None:
    """Update this CLI with uv tool."""

    command = ["uv", "tool", "upgrade", PACKAGE_NAME]
    if not shutil.which(command[0]):
        typer.secho(
            f"Error: '{command[0]}' is not available on PATH.",
            err=True,
            fg=typer.colors.RED,
        )
        raise typer.Exit(code=1)

    typer.echo(f"Current version: {__version__}")
    typer.echo(f"Selected command: {' '.join(command)}")
    if dry_run:
        return

    completed = subprocess.run(command, check=False)
    if completed.returncode != 0:
        raise typer.Exit(code=completed.returncode)


def main() -> None:
    app()
