#!/bin/bash
# MORPH-SPEC Pre-Commit Hook: Test Coverage
# Ensures new code has corresponding tests

echo "🧪 Checking test coverage..."

# Find modified C# files (excluding tests)
CS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.cs$' | grep -v 'Tests\|Test\.cs$')

if [ -z "$CS_FILES" ]; then
  echo "✓ No production code modified"
  exit 0
fi

MISSING_TESTS=false

for cs_file in $CS_FILES; do
  # Extract class name
  class_name=$(basename "$cs_file" .cs)

  # Look for corresponding test file
  test_patterns=(
    "*/${class_name}Tests.cs"
    "*/${class_name}Test.cs"
    "*/Test${class_name}.cs"
  )

  FOUND_TEST=false
  for pattern in "${test_patterns[@]}"; do
    if find . -path "$pattern" 2>/dev/null | grep -q .; then
      FOUND_TEST=true
      break
    fi
  done

  if [ "$FOUND_TEST" = false ]; then
    # Check if it's a trivial file (DTO, model, etc.)
    if grep -qi 'record\|DTO\|Model\|Entity' "$cs_file" && ! grep -qi 'class.*{.*public.*{' "$cs_file"; then
      echo "  ℹ️  Skipping trivial file: $cs_file"
      continue
    fi

    echo "  ⚠️  No test found for: $cs_file"
    MISSING_TESTS=true
  else
    echo "  ✓ Test found for: $cs_file"
  fi
done

if [ "$MISSING_TESTS" = true ]; then
  echo ""
  echo "⚠️  WARNING: Some files don't have tests"
  echo "   Consider adding tests before committing"
  echo "   Override with: git commit --no-verify"
  # Don't block, just warn
  exit 0
fi

echo "✓ Test coverage looks good"
exit 0
