#!/usr/bin/env bash
set -euo pipefail

LANG=${1:?usage: loop-guard.sh <lang>}
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
mkdir -p .loop-locks .loop-logs
LOCK=".loop-locks/$LANG.claim"
LOG=".loop-logs/$LANG.ndjson"
NOW=$(date +%s)
ISO=$(date -Iseconds)
STALE_SEC=${LOOP_STALE_SEC:-1800}

if [ -f "$LOCK" ]; then
  LAST=$(cat "$LOCK" 2>/dev/null || echo 0)
  AGE=$((NOW - LAST))
  if [ "$AGE" -lt "$STALE_SEC" ]; then
    printf '{"ts":"%s","lang":"%s","status":"skip","age":%d}\n' "$ISO" "$LANG" "$AGE" >> "$LOG"
    echo "SKIP: $LANG claimed ${AGE}s ago (stale threshold ${STALE_SEC}s)"
    exit 1
  fi
  echo "INFO: $LANG lock was ${AGE}s old, overtaking"
fi

echo "$NOW" > "$LOCK"
printf '{"ts":"%s","lang":"%s","status":"claimed"}\n' "$ISO" "$LANG" >> "$LOG"
echo "OK: $LANG claimed at $ISO"
