#!/bin/bash
# Pre-push QC: reads ERROR_LOG.md, computes 1SD and 2SD thresholds.
# - Above 1SD: flags as warning (verify not repeated in this push)
# - Above 2SD: suggests promoting to LEARNINGS.md (pattern is systemic)
# Called by PreToolUse hook when Bash command contains "git push".

INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // ""')

# Only run for git push commands
if ! echo "$CMD" | grep -qE 'git push'; then
  exit 0
fi

LOG="docs/ERROR_LOG.md"
if [ ! -f "$LOG" ]; then
  exit 0
fi

# Extract Count values only from non-promoted ERR-XXX entries (skip template + promoted)
COUNTS=$(awk '/^## ERR-[0-9]/{promoted=($0 ~ /PROMOTED/); in_entry=1} in_entry && !promoted && /^- Count:/{match($0,/[0-9]+/); print substr($0,RSTART,RLENGTH)}' "$LOG")
N=$(echo "$COUNTS" | grep -c '[0-9]' 2>/dev/null || echo 0)

# Need at least 3 data points for SD to be meaningful
if [ "$N" -lt 3 ]; then
  exit 0
fi

# Calculate mean, 1SD threshold, and 2SD threshold in one awk pass
read -r THRESHOLD_1SD THRESHOLD_2SD <<< "$(echo "$COUNTS" | awk '
  { sum += $1; vals[NR] = $1; n++ }
  END {
    mean = sum / n
    for (i in vals) sq += (vals[i] - mean)^2
    sd = sqrt(sq / n)
    printf "%.2f %.2f", mean + sd, mean + 2*sd
  }
')"

# Find errors above 1SD — these are high-frequency warnings
HIGH=$(awk -v thresh="$THRESHOLD_1SD" '
  BEGIN { title=""; count=0; fix=""; promoted=0 }
  /^## ERR-[0-9]/ {
    if (title != "" && !promoted && count+0 > thresh+0 && fix != "")
      printf "  • %s (x%d) — %s\n", title, count, fix
    title = substr($0, 4); count = 0; fix = ""; promoted = ($0 ~ /PROMOTED/)
  }
  /^- Count:/  { match($0, /[0-9]+/); count = substr($0, RSTART, RLENGTH) + 0 }
  /^- Fix:/    { fix = substr($0, index($0, $3)) }
  END {
    if (title != "" && !promoted && count+0 > thresh+0 && fix != "")
      printf "  • %s (x%d) — %s\n", title, count, fix
  }
' "$LOG")

# Find errors above 2SD — these should be promoted to LEARNINGS.md
PROMOTE=$(awk -v thresh="$THRESHOLD_2SD" '
  BEGIN { title=""; count=0; promoted=0 }
  /^## ERR-[0-9]/ {
    if (title != "" && !promoted && count+0 > thresh+0)
      printf "  → %s (x%d)\n", title, count
    title = substr($0, 4); count = 0; promoted = ($0 ~ /PROMOTED/)
  }
  /^- Count:/ { match($0, /[0-9]+/); count = substr($0, RSTART, RLENGTH) + 0 }
  END {
    if (title != "" && !promoted && count+0 > thresh+0)
      printf "  → %s (x%d)\n", title, count
  }
' "$LOG")

# Nothing above 1SD — allow push silently
if [ -z "$HIGH" ]; then
  exit 0
fi

# Build message with 1SD warnings + optional 2SD promote suggestion
MSG=$(printf '⚠ Pre-push QC (1SD=%.1f) — Verify not repeated in this push:\n%s' "$THRESHOLD_1SD" "$HIGH")

if [ -n "$PROMOTE" ]; then
  MSG=$(printf '%s\n\n🔺 Above 2SD (=%.1f) — Consider promoting to docs/LEARNINGS.md:\n%s\n  Run "summarize learnings" to promote these into golden rules + Check: patterns.' \
    "$MSG" "$THRESHOLD_2SD" "$PROMOTE")
fi

printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"%s"}}' \
  "$(echo "$MSG" | python3 -c "import sys,json; print(json.dumps(sys.stdin.read())[1:-1])" 2>/dev/null \
  || echo "$MSG" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr '\n' ' ')"
