#!/bin/bash
# Ralph Wiggum Quality Gate Hook
# ================================
# Intercepts agent completion and verifies quality before allowing exit.
# Named after the "Ralph Wiggum" iterative pattern for Claude Code.
#
# How it works:
# 1. After Builder/Debugger/Refactor agents finish writing code
# 2. This hook runs quality checks (type-check, lint, test)
# 3. If checks fail, it returns feedback so the agent self-corrects
# 4. If checks pass (or max iterations reached), it allows completion
#
# The hook looks for a "completion promise" in the agent's output —
# the phrase "QUALITY GATE PASSED" signals the agent has verified its work.
#
# Configure which checks run by editing the CHECKS array below.
# NOTE: This script needs chmod +x to be executable

# Read the tool input from stdin
INPUT=$(cat)

# Extract the file that was just written/edited
FILE_PATH=$(echo "$INPUT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',{}).get('file_path',''))" 2>/dev/null)

# Only run quality checks on source code files
case "$FILE_PATH" in
    *.ts|*.tsx|*.js|*.jsx|*.py|*.rs|*.go)
        # This is a source file — run quality checks
        ;;
    *)
        # Not source code (markdown, json, config, etc.) — skip
        exit 0
        ;;
esac

# Find project root
PROJECT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"

# Track iteration count via temp file
ITERATION_FILE="/tmp/ralph-wiggum-iterations-$$"
if [ -f "$ITERATION_FILE" ]; then
    ITERATIONS=$(cat "$ITERATION_FILE")
else
    ITERATIONS=0
fi
ITERATIONS=$((ITERATIONS + 1))
echo "$ITERATIONS" > "$ITERATION_FILE"

MAX_ITERATIONS=3

# If we've hit max iterations, allow completion regardless
if [ "$ITERATIONS" -ge "$MAX_ITERATIONS" ]; then
    rm -f "$ITERATION_FILE"
    exit 0
fi

# ═══════════════════════════════════════════════════════════════════
# QUALITY CHECKS — Edit these for your project
# ═══════════════════════════════════════════════════════════════════

ERRORS=""

# Check 1: TypeScript type checking (if tsconfig exists)
if [ -f "$PROJECT_DIR/tsconfig.json" ]; then
    TS_OUTPUT=$(cd "$PROJECT_DIR" && npx tsc --noEmit 2>&1)
    if [ $? -ne 0 ]; then
        # Count errors
        ERROR_COUNT=$(echo "$TS_OUTPUT" | grep -c "error TS")
        ERRORS="${ERRORS}TypeScript: ${ERROR_COUNT} type errors found.\n"
    fi
fi

# Check 2: Linting (if eslint config exists)
if [ -f "$PROJECT_DIR/.eslintrc.js" ] || [ -f "$PROJECT_DIR/.eslintrc.json" ] || [ -f "$PROJECT_DIR/eslint.config.js" ]; then
    LINT_OUTPUT=$(cd "$PROJECT_DIR" && npx eslint "$FILE_PATH" 2>&1)
    if [ $? -ne 0 ]; then
        LINT_ERRORS=$(echo "$LINT_OUTPUT" | grep -c "error")
        ERRORS="${ERRORS}ESLint: ${LINT_ERRORS} lint errors in ${FILE_PATH}.\n"
    fi
fi

# Check 3: Python syntax check (for .py files)
if [[ "$FILE_PATH" == *.py ]]; then
    PY_OUTPUT=$(python3 -m py_compile "$FILE_PATH" 2>&1)
    if [ $? -ne 0 ]; then
        ERRORS="${ERRORS}Python: Syntax error in ${FILE_PATH}.\n"
    fi
fi

# ═══════════════════════════════════════════════════════════════════
# VERDICT
# ═══════════════════════════════════════════════════════════════════

if [ -n "$ERRORS" ]; then
    # Quality gate FAILED — feed errors back
    echo "RALPH WIGGUM QUALITY GATE (iteration $ITERATIONS/$MAX_ITERATIONS):"
    echo -e "$ERRORS"
    echo "Fix these issues before continuing. Run checks again after fixing."
    # Don't exit with error — just provide feedback
    exit 0
else
    # Quality gate PASSED — clean up and allow completion
    rm -f "$ITERATION_FILE"
    exit 0
fi
