#!/bin/sh
set -eu

codex_home="${CODEX_HOME:-/tmp/auto-oncall-codex}"
retention_days="${AUTO_ONCALL_CODEX_HISTORY_RETENTION_DAYS:-30}"

case "$retention_days" in
  ''|*[!0-9]*)
    echo "AUTO_ONCALL_CODEX_HISTORY_RETENTION_DAYS must be a positive integer" >&2
    exit 1
    ;;
esac
if [ "$retention_days" -le 0 ]; then
  echo "AUTO_ONCALL_CODEX_HISTORY_RETENTION_DAYS must be a positive integer" >&2
  exit 1
fi
if [ -z "$codex_home" ] || [ "$codex_home" = "/" ]; then
  echo "CODEX_HOME must identify a dedicated Codex directory" >&2
  exit 1
fi
if ! command -v sqlite3 >/dev/null 2>&1; then
  echo "sqlite3 is required to clean the Codex thread index" >&2
  exit 1
fi

retention_minutes=$((retention_days * 24 * 60))
cutoff_seconds=$(date -u -d "$retention_days days ago" +%s)
cutoff_milliseconds=$((cutoff_seconds * 1000))
state_db="${codex_home%/}/state_5.sqlite"

deleted_threads=0
if [ -f "$state_db" ]; then
  deleted_threads=$(sqlite3 -batch "$state_db" <<SQL
.timeout 30000
BEGIN IMMEDIATE;
CREATE TEMP TABLE expired_thread_ids AS
SELECT id
FROM threads
WHERE COALESCE(NULLIF(updated_at_ms, 0), updated_at * 1000) < $cutoff_milliseconds;
DELETE FROM thread_dynamic_tools
WHERE thread_id IN (SELECT id FROM expired_thread_ids);
DELETE FROM thread_spawn_edges
WHERE parent_thread_id IN (SELECT id FROM expired_thread_ids)
   OR child_thread_id IN (SELECT id FROM expired_thread_ids);
DELETE FROM threads
WHERE id IN (SELECT id FROM expired_thread_ids);
SELECT count(*) FROM expired_thread_ids;
COMMIT;
PRAGMA incremental_vacuum;
SQL
  )
fi

deleted_files=0
deleted_bytes=0
for history_root in \
  "${codex_home%/}/sessions" \
  "${codex_home%/}/archived_sessions"
do
  [ -d "$history_root" ] || continue
  root_files=$(find "$history_root" -xdev -type f -name 'rollout-*.jsonl' \
    -mmin "+$retention_minutes" | wc -l)
  root_bytes=$(find "$history_root" -xdev -type f -name 'rollout-*.jsonl' \
    -mmin "+$retention_minutes" -printf '%s\n' \
    | awk '{total += $1} END {print total + 0}')
  find "$history_root" -xdev -type f -name 'rollout-*.jsonl' \
    -mmin "+$retention_minutes" -delete
  find "$history_root" -xdev -depth -mindepth 1 -type d -empty -delete
  deleted_files=$((deleted_files + root_files))
  deleted_bytes=$((deleted_bytes + root_bytes))
done

echo "codex history cleanup complete: retention_days=$retention_days deleted_threads=$deleted_threads deleted_files=$deleted_files deleted_bytes=$deleted_bytes"
