#!/bin/sh
#
# SpecWeave Pre-Commit Hook (User Projects)
# Generated by: specweave init
# Version: 2.0.0
#
# This hook enforces SpecWeave best practices to prevent common mistakes.
# Checks run automatically on every commit to maintain code quality.
#
# To bypass temporarily: git commit --no-verify
# To disable permanently: rm .git/hooks/pre-commit
#

# Color codes for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "${BLUE}🔍 Running SpecWeave pre-commit checks...${NC}"
echo ""

# Track overall validation status
VALIDATION_FAILED=0

# ============================================================================
# CHECK 1: Root Folder Pollution (CRITICAL)
# ============================================================================
# Prevents .md and .log files from being created in project root
# Related: CLAUDE.md Rule #5 - "Root clean"

echo "1️⃣  Checking for root folder pollution..."

# Allowed root markdown files (standard project docs)
# Space-separated, not a bash array: /bin/sh is dash on Debian/Ubuntu and
# `ALLOWED_FILES=(...)` is a syntax error there, which aborts the whole hook.
ALLOWED_FILES="README.md CLAUDE.md AGENTS.md CHANGELOG.md LICENSE.md CODE_OF_CONDUCT.md SECURITY.md IMPLEMENTATION-SUMMARY.md IMPLEMENTATION-COMPLETE.md"

# Get staged markdown and log files in root (not in subdirectories)
STAGED_ROOT_FILES=$(git diff --cached --name-only --diff-filter=AM | grep -E '^[^/]*\.(md|log)$' || true)

if [ -n "$STAGED_ROOT_FILES" ]; then
  VIOLATIONS=""

  for file in $STAGED_ROOT_FILES; do
    # Check if file is in allowed list
    is_allowed=0
    for allowed in $ALLOWED_FILES; do
      if [ "$file" = "$allowed" ]; then
        is_allowed=1
        break
      fi
    done

    if [ $is_allowed -eq 0 ]; then
      VIOLATIONS="$VIOLATIONS\n  - $file"
    fi
  done

  if [ -n "$VIOLATIONS" ]; then
    echo "${RED}   ❌ Root pollution detected!${NC}"
    echo ""
    echo "   The following files violate SpecWeave clean root policy:"
    echo -e "$VIOLATIONS"
    echo ""
    echo "   ${YELLOW}Why this matters:${NC}"
    echo "   - Keeps project organized and professional"
    echo "   - Prevents git status clutter"
    echo "   - Follows SpecWeave best practices"
    echo ""
    echo "   ${GREEN}Where to move them:${NC}"
    echo "   - Analysis/reports     → .specweave/increments/####/reports/"
    echo "   - Session logs         → .specweave/increments/####/logs/"
    echo "   - Scripts/automation   → .specweave/increments/####/scripts/"
    echo ""
    echo "   ${BLUE}Quick fix:${NC}"
    echo "   # Find active increment"
    echo "   CURRENT=\$(ls -t .specweave/increments/ | head -1)"
    echo ""
    echo "   # Move files"
    echo "   mkdir -p .specweave/increments/\$CURRENT/reports/"
    for file in $STAGED_ROOT_FILES; do
      is_allowed=0
      for allowed in $ALLOWED_FILES; do
        if [ "$file" = "$allowed" ]; then
          is_allowed=1
          break
        fi
      done
      if [ $is_allowed -eq 0 ]; then
        echo "   mv $file .specweave/increments/\$CURRENT/reports/"
      fi
    done
    echo ""
    echo "   # Unstage old location, stage new location"
    for file in $STAGED_ROOT_FILES; do
      is_allowed=0
      for allowed in $ALLOWED_FILES; do
        if [ "$file" = "$allowed" ]; then
          is_allowed=1
          break
        fi
      done
      if [ $is_allowed -eq 0 ]; then
        echo "   git reset HEAD $file"
      fi
    done
    echo "   git add .specweave/increments/\$CURRENT/"
    echo ""
    VALIDATION_FAILED=1
  else
    echo "${GREEN}   ✓ No root pollution${NC}"
  fi
else
  echo "${GREEN}   ✓ No root pollution${NC}"
fi

echo ""

# ============================================================================
# CHECK 2: Increment Folder Cleanliness
# ============================================================================
# Ensures increment folders stay organized (only the canonical 2.0 artifacts at root)

# Generated from INCREMENT_ROOT_FILES (src/core/increment/increment-artifacts.ts)
ALLOWED_INCREMENT_ROOT_FILES="{{ALLOWED_INCREMENT_ROOT_FILES}}"

echo "2️⃣  Checking increment folder cleanliness..."

# Get staged files in increment directories
STAGED_INCREMENT_FILES=$(git diff --cached --name-only --diff-filter=AM | grep -E '\.specweave/increments/[0-9]{3,}[A-Za-z]?-' || true)

if [ -n "$STAGED_INCREMENT_FILES" ]; then
  POLLUTION_FOUND=0

  for file in $STAGED_INCREMENT_FILES; do
    # Extract increment directory and relative path within it
    increment_dir=$(echo "$file" | grep -oE '\.specweave/increments/[0-9]{3,}[A-Za-z]?-[^/]+' || true)
    if [ -n "$increment_dir" ]; then
      # Get path relative to increment directory
      relative_path=$(echo "$file" | sed "s|^$increment_dir/||")

      # Check if it's directly in increment root (no subdirectory)
      if ! echo "$relative_path" | grep -q '/'; then
        # File is at increment root - check if it's allowed
        filename=$(basename "$relative_path")
        # Membership test on the pipe-delimited allow-list. (A `case` pattern
        # cannot come from a variable: `|` is syntax, not data, so `case $f in
        # $LIST)` would compare against the literal string.)
        case "|$ALLOWED_INCREMENT_ROOT_FILES|" in
          *"|$filename|"*)
            # Allowed files
            ;;
          *)
            # Not allowed at increment root!
            if [ $POLLUTION_FOUND -eq 0 ]; then
              echo "${RED}   ❌ Increment folder pollution detected!${NC}"
              echo ""
              echo "   ${YELLOW}Only these files are allowed at an increment root:${NC}"
              echo "   ${YELLOW}   $(echo "$ALLOWED_INCREMENT_ROOT_FILES" | tr '|' ' ')${NC}"
              echo ""
              echo "   ${RED}Files in wrong location:${NC}"
              POLLUTION_FOUND=1
            fi
            echo "   - $file"
            echo "     → Should be in: $increment_dir/reports/ (or scripts/, logs/)"
            ;;
        esac
      fi
    fi
  done

  if [ $POLLUTION_FOUND -eq 1 ]; then
    echo ""
    echo "   ${BLUE}Organization rules:${NC}"
    echo "   - Reports/analysis     → reports/"
    echo "   - Scripts/automation   → scripts/"
    echo "   - Logs/execution output → logs/YYYY-MM-DD/"
    echo "   - Domain docs          → docs/domain/"
    echo ""
    VALIDATION_FAILED=1
  else
    echo "${GREEN}   ✓ Increment folders clean${NC}"
  fi
else
  echo "${GREEN}   ✓ No increment files staged${NC}"
fi

echo ""

# ============================================================================
# CHECK 3: Duplicate Increment Detection
# ============================================================================
# Prevents data corruption from duplicate increment IDs

echo "3️⃣  Checking for duplicate increment IDs..."

if [ -d ".specweave/increments" ]; then
  # Get all increment IDs across ALL directories (including _archive, _paused, etc.)
  # -name filters on the directory's OWN basename, so `0001-slug/reports`
  # (depth 2) is NOT counted as a second `0001` while `_archive/0002-slug` is.
  ALL_IDS=$(find .specweave/increments -maxdepth 2 -type d -name '[0-9]*-*' | \
    sed 's|.*/||' | grep -E '^[0-9]{3,}[A-Za-z]?-' | sed -E 's/^([0-9]+)[A-Za-z]?-.*/\1/; s/^0+//; s/^$/0/' | \
    sort)

  # Check for duplicates
  DUPLICATES=$(echo "$ALL_IDS" | uniq -d)

  if [ -n "$DUPLICATES" ]; then
    echo "${RED}   ❌ Duplicate increment IDs found!${NC}"
    echo ""
    for dup_id in $DUPLICATES; do
      echo "   ${RED}Duplicate ID: $dup_id${NC}"
      # Find all directories with this ID
      find .specweave/increments -maxdepth 2 -type d -name "${dup_id}-*" | while read -r dir; do
        echo "   - $dir"
      done
      echo ""
    done
    echo "   ${YELLOW}This is a critical issue!${NC}"
    echo "   Duplicate IDs cause:"
    echo "   - Data corruption"
    echo "   - Sync failures"
    echo "   - Living docs conflicts"
    echo ""
    echo "   ${BLUE}Fix:${NC} Renumber one of the duplicates to next available ID"
    echo ""
    VALIDATION_FAILED=1
  else
    echo "${GREEN}   ✓ No duplicates found${NC}"
  fi
else
  echo "${GREEN}   ✓ No increments directory${NC}"
fi

echo ""

# ============================================================================
# CHECK 4: YAML Frontmatter Validation (requires Node.js)
# ============================================================================
# Prevents malformed spec.md files

echo "4️⃣  Checking YAML frontmatter in spec.md files..."

# Check if Node.js is available
if command -v node >/dev/null 2>&1; then
  STAGED_SPECS=$(git diff --cached --name-only --diff-filter=ACM | grep 'spec\.md$' || true)

  if [ -n "$STAGED_SPECS" ]; then
    YAML_ERRORS=0

    for spec_file in $STAGED_SPECS; do
      # Skip if file doesn't exist (deleted)
      if [ ! -f "$spec_file" ]; then
        continue
      fi

      # Check if file has YAML frontmatter
      if head -1 "$spec_file" | grep -q '^---$'; then
        # Extract frontmatter (between first and second ---)
        frontmatter=$(awk '/^---$/{i++}i==1' "$spec_file" | sed '1d;$d' || true)

        if [ -n "$frontmatter" ]; then
          # Try to parse with Node.js (if js-yaml is available)
          # Use --input-type=commonjs to handle ESM projects
          if node --input-type=commonjs -e "require('js-yaml')" >/dev/null 2>&1; then
            echo "$frontmatter" | node --input-type=commonjs -e "
              const yaml = require('js-yaml');
              let input = '';
              process.stdin.on('data', chunk => input += chunk);
              process.stdin.on('end', () => {
                try {
                  const data = yaml.load(input);
                  if (!data.increment) {
                    console.error('Missing required field: increment');
                    process.exit(1);
                  }
                } catch (e) {
                  console.error('YAML parse error:', e.message);
                  process.exit(1);
                }
              });
            " 2>/dev/null

            if [ $? -ne 0 ]; then
              if [ $YAML_ERRORS -eq 0 ]; then
                echo "${RED}   ❌ YAML validation failed!${NC}"
                echo ""
              fi
              echo "   ${RED}Invalid YAML in: $spec_file${NC}"
              YAML_ERRORS=1
            fi
          fi
        fi
      fi
    done

    if [ $YAML_ERRORS -eq 0 ]; then
      echo "${GREEN}   ✓ All YAML valid${NC}"
    else
      echo ""
      echo "   ${BLUE}Fix:${NC} Ensure YAML frontmatter is properly formatted"
      echo "   Required format:"
      echo "   ---"
      echo "   increment: ####-feature-name"
      echo "   title: \"Feature Title\""
      echo "   ---"
      echo ""
      VALIDATION_FAILED=1
    fi
  else
    echo "${GREEN}   ✓ No spec.md files staged${NC}"
  fi
else
  echo "${YELLOW}   ⚠ Skipped (Node.js not found)${NC}"
fi

echo ""

# ============================================================================
# CHECK 5: Mass .specweave/ Deletion Protection
# ============================================================================
# Prevents accidental deletion of entire .specweave folder

echo "5️⃣  Checking for mass .specweave/ deletion..."

DELETED_COUNT=$(git status --short | grep "^ D .specweave/" | wc -l | tr -d ' ')
THRESHOLD=50

if [ "$DELETED_COUNT" -gt "$THRESHOLD" ]; then
  echo "${RED}   ❌ Mass deletion detected!${NC}"
  echo ""
  echo "   Attempting to delete $DELETED_COUNT files in .specweave/"
  echo "   Threshold: $THRESHOLD files"
  echo ""
  echo "   ${YELLOW}This likely indicates:${NC}"
  echo "   1. Test cleanup deleted real .specweave/ folder"
  echo "   2. Accidental 'rm -rf .specweave/'"
  echo ""
  echo "   ${BLUE}To restore:${NC} git restore .specweave/"
  echo ""
  VALIDATION_FAILED=1
else
  echo "${GREEN}   ✓ No mass deletion${NC}"
fi

echo ""

# ============================================================================
# FINAL RESULT
# ============================================================================

if [ $VALIDATION_FAILED -eq 1 ]; then
  echo ""
  echo "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo "${RED}❌ VALIDATION FAILED - COMMIT BLOCKED${NC}"
  echo "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo "   Fix the errors above before committing."
  echo ""
  echo "   ${YELLOW}To bypass this check (NOT RECOMMENDED):${NC}"
  echo "   git commit --no-verify"
  echo ""
  echo "   ${BLUE}To disable this hook permanently:${NC}"
  echo "   rm .git/hooks/pre-commit"
  echo ""
  echo "   ${BLUE}For help:${NC} See CLAUDE.md or AGENTS.md for SpecWeave rules"
  echo ""
  exit 1
fi

echo "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo "${GREEN}✅ All checks passed - commit allowed${NC}"
echo "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
exit 0
