import sys
import time


class _ProgressBar:
    """Progress bar for experiment execution.

    Uses tqdm if available, falls back to a simple stderr line display.
    """

    def __init__(self, total: int | None, desc: str) -> None:
        self._desc = desc
        self._n = 0
        self._total = total
        self._start = time.monotonic()
        self._tqdm = None
        try:
            from tqdm import tqdm  # noqa: PLC0415

            self._tqdm = tqdm(
                total=total,
                desc=f"Running '{desc}'",
                unit="run",
                dynamic_ncols=True,
            )
        except ImportError:
            self._render()

    def update(self, n: int = 1) -> None:
        self._n += n
        if self._tqdm is not None:
            self._tqdm.update(n)
        else:
            self._render()

    def set_total(self, total: int) -> None:
        self._total = total
        if self._tqdm is not None:
            self._tqdm.total = total
            self._tqdm.refresh()

    def close(self) -> None:
        if self._tqdm is not None:
            self._tqdm.close()
        else:
            print(file=sys.stderr)

    def _render(self) -> None:
        elapsed = int(time.monotonic() - self._start)
        mins, secs = divmod(elapsed, 60)
        elapsed_str = f"{mins:02d}:{secs:02d}"
        total_str = str(self._total) if self._total else "?"
        line = f"\rRunning '{self._desc}': {self._n}/{total_str} runs [{elapsed_str} elapsed]"
        print(line, end="", flush=True, file=sys.stderr)
