#!/bin/sh
# Healthcheck: verify the planner-agent heartbeat is fresh.
# The planner touches /opt/homelab/state/planner-agent.heartbeat
# at the top of every poll cycle (≤5 s intervals).
# We fail if it is older than 300 s (5 min = one full cooldown window).

HEARTBEAT_FILE="${RUNTIME_PATH:-/opt/homelab}/state/planner-agent.heartbeat"
MAX_AGE_SECONDS=300

if [ ! -f "$HEARTBEAT_FILE" ]; then
    echo "FAIL: heartbeat file missing: $HEARTBEAT_FILE"
    exit 1
fi

NOW=$(date +%s)
FILE_TIME=$(stat -c %Y "$HEARTBEAT_FILE" 2>/dev/null) || {
    echo "FAIL: cannot stat heartbeat file"
    exit 1
}
AGE=$((NOW - FILE_TIME))

if [ "$AGE" -gt "$MAX_AGE_SECONDS" ]; then
    echo "FAIL: heartbeat stale (${AGE}s > ${MAX_AGE_SECONDS}s)"
    exit 1
fi

echo "OK: heartbeat age ${AGE}s"
exit 0
