#!/bin/bash
# Smoke test for all hook scripts.
# Verifies: syntax, Python detection, graceful handling of empty/malformed input.
# Run: bash hooks/test-hooks.sh
#
# This script does NOT test hook logic (e.g., whether block-git-push actually blocks).
# It tests that hooks don't crash, always exit 0, and handle bad input gracefully.

PASS=0
FAIL=0
SKIP=0

pass() { echo "  PASS: $1"; PASS=$((PASS + 1)); }
fail() { echo "  FAIL: $1"; FAIL=$((FAIL + 1)); }
skip() { echo "  SKIP: $1"; SKIP=$((SKIP + 1)); }

HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Hook Smoke Tests ==="
echo "Directory: $HOOKS_DIR"
echo ""

# 1. Syntax check
echo "--- Syntax Check ---"
for f in "$HOOKS_DIR"/*.sh; do
  name=$(basename "$f")
  [ "$name" = "test-hooks.sh" ] && continue
  if bash -n "$f" 2>/dev/null; then
    pass "$name syntax"
  else
    fail "$name syntax"
  fi
done
echo ""

# 2. Python detection (should not crash if Python missing)
echo "--- Python Detection ---"
PYTHON=$(command -v python3 2>/dev/null || command -v python 2>/dev/null)
if [ -n "$PYTHON" ]; then
  pass "Python found: $PYTHON"
else
  skip "Python not found -- hooks will skip JSON parsing (expected behavior)"
fi
echo ""

# 3. Empty input test (every hook should exit 0 on empty stdin)
echo "--- Empty Input (exit 0 expected) ---"
for f in "$HOOKS_DIR"/*.sh; do
  name=$(basename "$f")
  [ "$name" = "test-hooks.sh" ] && continue
  [ "$name" = "status-line.sh" ] && continue  # status-line reads no stdin
  [ "$name" = "verify-mcp-sync.sh" ] && continue  # reads files, not stdin
  echo "" | bash "$f" > /dev/null 2>&1
  code=$?
  if [ $code -eq 0 ]; then
    pass "$name empty input (exit $code)"
  else
    fail "$name empty input (exit $code, expected 0)"
  fi
done
echo ""

# 4. Malformed JSON input test
echo "--- Malformed JSON Input (exit 0 expected) ---"
for f in "$HOOKS_DIR"/*.sh; do
  name=$(basename "$f")
  [ "$name" = "test-hooks.sh" ] && continue
  [ "$name" = "status-line.sh" ] && continue
  [ "$name" = "verify-mcp-sync.sh" ] && continue
  echo "not valid json {{{" | bash "$f" > /dev/null 2>&1
  code=$?
  if [ $code -eq 0 ]; then
    pass "$name malformed JSON (exit $code)"
  else
    fail "$name malformed JSON (exit $code, expected 0)"
  fi
done
echo ""

# 5. Valid JSON but missing fields
echo "--- Valid JSON, Missing Fields (exit 0 expected) ---"
for f in "$HOOKS_DIR"/*.sh; do
  name=$(basename "$f")
  [ "$name" = "test-hooks.sh" ] && continue
  [ "$name" = "status-line.sh" ] && continue
  [ "$name" = "verify-mcp-sync.sh" ] && continue
  echo '{"tool_input":{}}' | bash "$f" > /dev/null 2>&1
  code=$?
  if [ $code -eq 0 ]; then
    pass "$name missing fields (exit $code)"
  else
    fail "$name missing fields (exit $code, expected 0)"
  fi
done
echo ""

# Summary
echo "=== Results ==="
echo "PASS: $PASS"
echo "FAIL: $FAIL"
echo "SKIP: $SKIP"
echo ""

if [ $FAIL -gt 0 ]; then
  echo "Some tests failed. Check the output above."
  exit 1
else
  echo "All tests passed."
  exit 0
fi
