#!/usr/bin/env bash
# Mnemosyne — Kintsugi Log Stale Shard Dismissal Accumulation Auditor
#
# kintsugi_log accumulates 'clean+0-bar' entries that suppress re-repair
# of the same shard for 30 days (_get_dismissed_set() lookback window).
# Under normal operation with Aletheia running, this count should remain
# near zero. Accumulation above 50 indicates Aletheia is not clearing
# artifacts fast enough, or genuinely sub-threshold shards are present.
#
# This check also reports the table's total size and age spread, which
# matters for ClickHouse parts pressure and query latency at scale.
#
# Escalation levels:
#   >200 unique dismissed shards — FAIL (likely blocking significant history)
#   >50 unique dismissed shards  — WARN (accumulating, investigate)
#   Old dismissed shards (7-30d) — informational: genuine sub-threshold if >0
set -euo pipefail

CH="http://localhost:8123/"

# Total dismissed unique shards in the 30-day active window
total_dismissed=$(curl -sf "$CH" --data-binary \
  "SELECT uniq(gap_start_ms) FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'clean' AND bars_written = 0
   AND timestamp > now() - INTERVAL 30 DAY" | tr -d '[:space:]')

# Entries 7-30 days old (outside race-artifact 2h window but still blocking)
old_dismissed=$(curl -sf "$CH" --data-binary \
  "SELECT uniq(gap_start_ms) FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'clean' AND bars_written = 0
   AND timestamp BETWEEN now() - INTERVAL 30 DAY AND now() - INTERVAL 7 DAY" | tr -d '[:space:]')

# Total kintsugi_log size (all rows, all results)
total_entries=$(curl -sf "$CH" --data-binary \
  "SELECT count() FROM opendeviationbar_cache.kintsugi_log" | tr -d '[:space:]')

# Log age spread (oldest entry shows how far back the log goes)
oldest=$(curl -sf "$CH" --data-binary \
  "SELECT min(toDate(timestamp)) FROM opendeviationbar_cache.kintsugi_log" | tr -d '[:space:]')

echo "Mnemosyne (kintsugi_log stale shard dismissal accumulation auditor)"
echo "  Total log entries:              $total_entries"
echo "  Oldest entry date:              $oldest"
echo "  Dismissed unique shards (30d):  $total_dismissed  (warn >50, fail >200)"
echo "  Old dismissed shards (7-30d):   $old_dismissed  (genuinely sub-threshold if >0 and Aletheia passing)"

if   [[ "$total_dismissed" -gt 200 ]]; then
  echo "  Status: FAIL — $total_dismissed dismissed shards is alarming. Run Aletheia purge or TRUNCATE kintsugi_log if table is stale."
  exit 2
elif [[ "$total_dismissed" -gt 50 ]]; then
  echo "  Status: WARN — $total_dismissed dismissed shards accumulating. Run Aletheia check first; if no race artifacts, genuine sub-threshold gaps present."
  exit 1
else
  echo "  Status: PASS"
  exit 0
fi
