#!/usr/bin/env bash
# Monotonic readiness deadline helpers. Source this file; it has no side effects.

monotonic_milliseconds() {
  local uptime whole fraction
  IFS=' ' read -r uptime _ </proc/uptime || return 1
  whole=${uptime%%.*}
  fraction=${uptime#*.}000
  fraction=${fraction:0:3}
  [[ "$whole" =~ ^[0-9]+$ && "$fraction" =~ ^[0-9]{3}$ ]] || return 1
  printf '%s\n' "$((10#$whole * 1000 + 10#$fraction))"
}

readiness_sleep() {
  local milliseconds=$1
  sleep "$((milliseconds / 1000)).$(printf '%03d' "$((milliseconds % 1000))")"
}

# wait_for_readiness <timeout-seconds> <interval-seconds> <probe> [args...]
# The probe runs immediately. READINESS_ELAPSED_MS and READINESS_ATTEMPTS describe the
# terminal verdict. One bounded in-flight probe may finish just after the deadline.
# Outputs are intentionally global evidence for callers of this sourced helper.
# shellcheck disable=SC2034
wait_for_readiness() {
  local timeout=$1 interval=$2
  shift 2
  local started now deadline remaining sleep_ms
  [[ "$timeout" =~ ^[1-9][0-9]*$ && "$interval" =~ ^[1-9][0-9]*$ && $# -gt 0 ]] || return 2
  started=$(monotonic_milliseconds) || return 2
  deadline=$((started + timeout * 1000))
  READINESS_ATTEMPTS=0
  READINESS_ELAPSED_MS=0
  while true; do
    READINESS_ATTEMPTS=$((READINESS_ATTEMPTS + 1))
    if "$@"; then
      now=$(monotonic_milliseconds) || return 2
      READINESS_ELAPSED_MS=$((now - started))
      return 0
    fi
    now=$(monotonic_milliseconds) || return 2
    READINESS_ELAPSED_MS=$((now - started))
    (( now < deadline )) || return 1
    remaining=$((deadline - now))
    sleep_ms=$((interval * 1000))
    (( sleep_ms <= remaining )) || sleep_ms=$remaining
    readiness_sleep "$sleep_ms" || return 2
    now=$(monotonic_milliseconds) || return 2
    READINESS_ELAPSED_MS=$((now - started))
    (( now < deadline )) || return 1
  done
}
