#!/bin/bash
# Pre-commit quality check: catches anti-patterns in staged files before commit.
#
# Two layers of checks:
#   1. Hard-coded rules (TypeScript any, auto-fetch, dark theme violations)
#   2. Dynamic rules from docs/LEARNINGS.md "- Check: <pattern> | <message>" lines
#
# Layer 2 is the "advancing" part — as LEARNINGS grows, this script automatically
# gets stricter without any manual updates.

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

# Only fire on git commit commands
if ! echo "$CMD" | grep -qE 'git commit'; then
  exit 0
fi

VIOLATIONS=""

# --- Get staged files ---
STAGED_TS=$(git diff --cached --name-only 2>/dev/null | grep -E '\.(ts|tsx)$' || true)
# Exclude docs/markdown from code checks — they legitimately reference forbidden patterns as examples
STAGED_ALL=$(git diff --cached --name-only 2>/dev/null | grep -vE '\.(md|mdx)$' || true)

# --- Layer 1: Hard-coded rules ---

# Rule: No TypeScript 'any' (use proper types or unknown)
if [ -n "$STAGED_TS" ]; then
  ANY_FILES=$(echo "$STAGED_TS" | tr '\n' '\0' | xargs -0 grep -l ': any\b' 2>/dev/null | head -3 || true)
  [ -n "$ANY_FILES" ] && VIOLATIONS="${VIOLATIONS}\n  • TypeScript 'any' in: $(echo "$ANY_FILES" | tr '\n' ' ')"
fi

# Rule: No auto-fetch on mount — useEffect + fetch in same file is a signal
if [ -n "$STAGED_TS" ]; then
  # Check files that have both useEffect and fetch( — heuristic, catches most cases
  UE_FILES=$(echo "$STAGED_TS" | tr '\n' '\0' | xargs -0 grep -l 'useEffect' 2>/dev/null || true)
  if [ -n "$UE_FILES" ]; then
    FETCH_FILES=$(echo "$UE_FILES" | tr '\n' '\0' | xargs -0 grep -l 'fetch(' 2>/dev/null | head -3 || true)
    [ -n "$FETCH_FILES" ] && VIOLATIONS="${VIOLATIONS}\n  • Possible auto-fetch in useEffect in: $(echo "$FETCH_FILES" | tr '\n' ' ') — verify it's user-triggered"
  fi
fi

# Rule: No solid dark hover colors (ERR-001 pattern)
if [ -n "$STAGED_ALL" ]; then
  DARK_FILES=$(echo "$STAGED_ALL" | tr '\n' '\0' | xargs -0 grep -lE 'dark:hover:bg-slate-[0-9]|dark:bg-slate-[0-9]{3}[^/]' 2>/dev/null | head -3 || true)
  [ -n "$DARK_FILES" ] && VIOLATIONS="${VIOLATIONS}\n  • Solid dark bg/hover color in: $(echo "$DARK_FILES" | tr '\n' ' ') — use opacity values (white/[0.02])"
fi

# --- Layer 2: Dynamic rules from LEARNINGS.md ---
# Format in LEARNINGS.md: "- Check: <grep_pattern> | <violation message>"
# Example: "- Check: overflow-auto | Canvas used overflow-auto — use transform instead"
#
# As LEARNINGS grows, this loop automatically adds more checks with zero manual effort.
if [ -f "docs/LEARNINGS.md" ]; then
  while IFS= read -r line; do
    PATTERN=$(echo "$line" | sed 's/^- Check: //' | cut -d'|' -f1 | sed 's/[[:space:]]*$//')
    MESSAGE=$(echo "$line" | cut -d'|' -f2 | sed 's/^[[:space:]]*//')
    if [ -n "$PATTERN" ] && [ -n "$STAGED_ALL" ]; then
      HITS=$(echo "$STAGED_ALL" | tr '\n' '\0' | xargs -0 grep -l "$PATTERN" 2>/dev/null | head -2 || true)
      [ -n "$HITS" ] && VIOLATIONS="${VIOLATIONS}\n  • ${MESSAGE} in: $(echo "$HITS" | tr '\n' ' ')"
    fi
  done < <(grep '^- Check: ' docs/LEARNINGS.md 2>/dev/null)
fi

# --- Output ---
if [ -z "$VIOLATIONS" ]; then
  exit 0
fi

MSG=$(printf "Pre-commit Quality Check — violations in staged files:\n%s\n\nReview and fix before committing." "$VIOLATIONS")

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' ' ')"
