"""CLI wrapper for self update workflows."""

from __future__ import annotations

import os

import typer

from worai import __version__
from worai.update import check_for_update, command_to_string, run_upgrade_command

app = typer.Typer(add_completion=False, no_args_is_help=True)


@app.command("update", help="Check for updates and optionally upgrade worai.")
def update(
    check_only: bool = typer.Option(
        False,
        "--check-only",
        help="Only check for updates and print the suggested command.",
    ),
    yes: bool = typer.Option(
        False,
        "--yes",
        "-y",
        help="Run the upgrade command immediately.",
    ),
) -> None:
    result = check_for_update(__version__, env=os.environ, force_refresh=True)

    if result.latest_version is None:
        typer.echo("Unable to check for updates right now.")
        typer.echo(f"Suggested upgrade command: {command_to_string(result.upgrade_command)}")
        raise typer.Exit(code=1)

    if not result.update_available:
        typer.echo(f"worai is up to date ({result.current_version}).")
        return

    typer.echo(
        f"Update available: {result.current_version} -> {result.latest_version}"
    )
    typer.echo(f"Suggested command: {command_to_string(result.upgrade_command)}")

    if check_only or not yes:
        if not check_only:
            typer.echo("Re-run with --yes to apply the update now.")
        return

    typer.echo(f"Running: {command_to_string(result.upgrade_command)}")
    raise typer.Exit(code=run_upgrade_command(result.upgrade_command))
