"""Persistent control flags for the autonomous runner."""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path


def stop_after_current_path(abreka_dir: Path) -> Path:
    """Return the marker path for a queued graceful stop request."""
    return abreka_dir / ".stop_after_current"


def stop_after_current_requested(abreka_dir: Path) -> bool:
    """Return True when a graceful stop has been queued."""
    return stop_after_current_path(abreka_dir).is_file()


def request_stop_after_current(abreka_dir: Path) -> Path:
    """Queue a graceful stop after the current experiment finishes."""
    path = stop_after_current_path(abreka_dir)
    path.write_text(f"{datetime.now(timezone.utc).isoformat()}\n")
    return path


def consume_stop_after_current_request(abreka_dir: Path) -> bool:
    """Clear and acknowledge a queued graceful stop request."""
    path = stop_after_current_path(abreka_dir)
    if not path.is_file():
        return False
    path.unlink()
    return True
