#!/bin/zsh
set -euo pipefail

REPO="/Users/openclaw/.openclaw/workspace"
HEALTH_LOG="$REPO/tmp/git-checkpoint-health.log"
CHECKPOINT_LOG="$REPO/tmp/git-checkpoint.log"
MAX_AGE_HOURS="${1:-6}"

mkdir -p "$REPO/tmp"

hc_status="OK"
reasons=()

cd "$REPO"
git rev-parse --is-inside-work-tree >/dev/null || { hc_status="FAIL"; reasons+=("not_a_git_repo"); }

if [ "$hc_status" = "OK" ]; then
  now=$(date +%s)
  head_ts=$(git log -1 --format=%ct 2>/dev/null || echo 0)

  if [ "$head_ts" -eq 0 ]; then
    hc_status="FAIL"
    reasons+=("no_commits")
  else
    age_sec=$(( now - head_ts ))
    max_sec=$(( MAX_AGE_HOURS * 3600 ))
    if [ "$age_sec" -gt "$max_sec" ]; then
      hc_status="FAIL"
      reasons+=("stale_last_commit_${age_sec}s")
    fi
  fi

  if [ ! -f "$CHECKPOINT_LOG" ]; then
    hc_status="FAIL"
    reasons+=("missing_checkpoint_log")
  else
    if ! tail -n 200 "$CHECKPOINT_LOG" | grep -q "OK checkpoint"; then
      hc_status="FAIL"
      reasons+=("no_recent_ok_marker")
    fi
  fi
fi

head_hash=$(git rev-parse --short HEAD 2>/dev/null || echo "none")
line="[$(date '+%Y-%m-%d %H:%M:%S %Z')] $hc_status head=$head_hash"
if [ ${#reasons[@]} -gt 0 ]; then
  line="$line reasons=$(IFS=,; echo "${reasons[*]}")"
fi

echo "$line" >> "$HEALTH_LOG"

if [ "$hc_status" != "OK" ]; then
  exit 1
fi
