#!/usr/bin/env bash
# Charybdis — Kintsugi Repair Total Duration and Vision Download Saturation Monitor
#
# Parses repair_complete events from kintsugi.ndjson to track total repair
# duration (download + Rust processing + ClickHouse insert combined).
# Under normal conditions, a single repair takes 1-15s depending on shard
# size; if USB ethernet saturates during Vision ZIP download, durations spike.
#
# Field used: duration_s (repair_complete event)
# Baseline (single outer worker, Vision-mode): 5-15s/repair, ~83 repairs/hr
# Baseline (Parquet-cached, no download): 0.5-2s/repair, ~1600+/hr
#
# Duration spikes (>60s) while repairs/hr is low indicates Vision download
# saturation — reduce MAX_CONCURRENT_REPAIRS to relieve USB ethernet pressure.
set -euo pipefail

NDJSON="$HOME/opendeviationbar-py/logs/kintsugi.ndjson"

if [[ ! -f "$NDJSON" ]]; then
  echo "Charybdis (kintsugi repair duration and Vision download saturation monitor)"
  echo "  Status: SKIP — kintsugi.ndjson not found at $NDJSON"
  exit 0
fi

stats=$(tail -500 "$NDJSON" 2>/dev/null | python3 -c "
import sys, json, statistics
durations = []
for line in sys.stdin:
    try:
        e = json.loads(line)
        if e.get('event') != 'repair_complete':
            continue
        d = e.get('duration_s')
        if d is not None and float(d) > 0:
            durations.append(float(d))
    except (json.JSONDecodeError, ValueError):
        pass
if not durations:
    print('no_data 0 0 0')
else:
    print(f'{len(durations)} {statistics.median(durations):.2f} {max(durations):.2f} {statistics.mean(durations):.2f}')
")

read -r count p50 p_max avg <<< "$stats"

echo "Charybdis (kintsugi repair duration and Vision download saturation monitor)"
echo "  Sample size (last 500 events): $count repair_complete events"
echo "  Median repair duration:        ${p50}s  (Vision-mode baseline: 5-15s | Parquet-cached: 0.5-2s)"
echo "  Max repair duration:           ${p_max}s"
echo "  Mean repair duration:          ${avg}s"
echo "  Concurrent repairs setting:    $(grep KINTSUGI_MAX_CONCURRENT_REPAIRS ~/opendeviationbar-py/deploy/opendeviationbar.env 2>/dev/null | cut -d= -f2 || echo 'unknown') outer workers"

if [[ "$count" == "no_data" ]] || [[ "$count" -eq 0 ]]; then
  echo "  Status: SKIP — no repair_complete events in recent log (kintsugi idle or just started)"
  exit 0
elif (( $(echo "$p50 > 120.0" | bc -l) )); then
  echo "  Status: FAIL — median ${p50}s far exceeds baseline. Vision ZIPs likely not downloading. Check network + MAX_CONCURRENT_REPAIRS."
  exit 2
elif (( $(echo "$p50 > 60.0" | bc -l) )); then
  echo "  Status: WARN — median ${p50}s elevated. USB ethernet may be saturating. Consider reducing MAX_CONCURRENT_REPAIRS."
  exit 1
else
  echo "  Status: PASS"
  exit 0
fi
