"""abreka stop — queue a graceful stop for the autonomous runner."""

from __future__ import annotations

import click

from abreka.config import find_abreka_dir
from abreka.run_control import (
    request_stop_after_current,
    stop_after_current_requested,
)


@click.command("stop")
@click.option(
    "--after-current",
    is_flag=True,
    help="Finish the current experiment (including evaluate), then stop before starting a new one.",
)
def stop_cmd(after_current: bool):
    """Queue a graceful stop for an in-progress autonomous run."""
    if not after_current:
        raise click.ClickException("Specify --after-current.")

    abreka_dir = find_abreka_dir()
    already_requested = stop_after_current_requested(abreka_dir)
    request_stop_after_current(abreka_dir)

    if already_requested:
        click.echo(
            "Graceful stop already queued; "
            "ABREKA will stop after the current experiment completes."
        )
        return

    click.echo(
        "Queued graceful stop; "
        "ABREKA will stop after the current experiment completes."
    )
