#!/usr/bin/env bash

set -euo pipefail

SESSIONS_DIR="$HOME/.hermes/sessions"
EXPORT_DIR="$HOME/.timmy/training-data/dpo-pairs"

latest_session=$(find "$SESSIONS_DIR" -maxdepth 1 -name 'session_*.json' -type f -print 2>/dev/null | sort | tail -n 1)
latest_export=$(find "$EXPORT_DIR" -maxdepth 1 -name 'session_*.json' -type f -print 2>/dev/null | sort | tail -n 1)

echo "latest_session=${latest_session:-none}"
echo "latest_export=${latest_export:-none}"

if [ -z "${latest_session:-}" ]; then
  echo "status=ok"
  echo "reason=no sessions yet"
  exit 0
fi

if [ -z "${latest_export:-}" ]; then
  echo "status=lagging"
  echo "reason=no exports yet"
  exit 1
fi

session_mtime=$(stat -f '%m' "$latest_session")
export_mtime=$(stat -f '%m' "$latest_export")
lag_minutes=$(( (session_mtime - export_mtime) / 60 ))
if [ "$lag_minutes" -lt 0 ]; then
  lag_minutes=0
fi

echo "lag_minutes=$lag_minutes"

if [ "$lag_minutes" -gt 300 ]; then
  echo "status=lagging"
  echo "reason=exports more than 5 hours behind sessions"
  exit 1
fi

echo "status=ok"
echo "reason=exports within freshness window"
