#!/usr/bin/env bash
# Nemesis — Kintsugi Repair Throughput Regression and Near-Stall Detector
#
# Computes the actual repair rate (repairs/hour) over the last 1h and 6h
# windows from ClickHouse kintsugi_log. Compares against known baselines
# to detect regressions before they become full stalls:
#
#   Vision-mode baseline:        ~83 repairs/hr (USB ethernet + Rust + CH)
#   Parquet-cached baseline:  ~1600+ repairs/hr (local I/O, no download)
#
# Stall conditions (ordered by severity):
#   - 0 repairs + high dismissed-shard count  = FAIL (blocked by dismissals)
#   - Repairs were active in 6h but stopped   = WARN (possible crash/stall)
#   - Rate < 10/hr while repairs are running  = WARN (severe throughput loss)
#
# Note: 0 repairs with 0 dismissed shards is PASS (queue empty, healthy idle).
set -euo pipefail

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

healed_1h=$(curl -sf "$CH" --data-binary \
  "SELECT count() FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'healed'
   AND timestamp > now() - INTERVAL 1 HOUR" | tr -d '[:space:]')

healed_6h=$(curl -sf "$CH" --data-binary \
  "SELECT count() FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'healed'
   AND timestamp > now() - INTERVAL 6 HOUR" | tr -d '[:space:]')

bars_1h=$(curl -sf "$CH" --data-binary \
  "SELECT sum(bars_written) FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'healed'
   AND timestamp > now() - INTERVAL 1 HOUR" | tr -d '[:space:]')

dismissed_now=$(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:]')

rate_6h=$(echo "scale=1; $healed_6h / 6" | bc)

echo "Nemesis (kintsugi repair throughput regression and near-stall detector)"
echo "  Repairs last 1h:    $healed_1h  (${healed_1h}/hr)"
echo "  Repairs last 6h:    $healed_6h  (${rate_6h}/hr avg)"
echo "  Bars written 1h:    $bars_1h"
echo "  Dismissed shards:   $dismissed_now  (blocks work if high — see Aletheia check)"
echo "  Baseline Vision:    ~83/hr | Baseline Parquet-cached: ~1600+/hr"

if [[ "$dismissed_now" -gt 100 ]] && [[ "$healed_1h" -eq 0 ]]; then
  echo "  Status: FAIL — 0 repairs + $dismissed_now dismissed shards = blocked stall. Run Aletheia purge: truncate kintsugi_log or restart kintsugi."
  exit 2
elif [[ "$healed_6h" -gt 5 ]] && [[ "$healed_1h" -eq 0 ]]; then
  echo "  Status: WARN — repairs were running (${healed_6h} in 6h) but stopped in last hour. Possible crash or queue exhaustion."
  exit 1
elif [[ "$healed_1h" -eq 0 ]] && [[ "$dismissed_now" -eq 0 ]]; then
  echo "  Status: PASS — no repairs needed (queue empty or kintsugi sleeping between discovery passes)."
  exit 0
elif (( $(echo "$rate_6h < 10.0" | bc -l) )) && [[ "$healed_6h" -gt 0 ]]; then
  echo "  Status: WARN — ${rate_6h}/hr over last 6h is very low. Check Aletheia (dismissal stall) or Tantalus (lock contention)."
  exit 1
else
  echo "  Status: PASS"
  exit 0
fi
