#!/usr/bin/env bash
# SDD Framework pre-commit hook — enforces version bumps for .claude/ changes
# Installed to .git/hooks/pre-commit by sdd-setup-hooks.sh
# Compatible with bash 3.x (macOS default)
set -euo pipefail

VERSION_FILE="VERSION"
ERRORS=()

# Get staged files (--no-renames ensures renames appear as delete+add, not R status)
STAGED_FILES="$(git diff --cached --no-renames --name-only)"
if [[ -z "$STAGED_FILES" ]]; then
  exit 0
fi

# Filter to qualifying .claude/ files (exclude learnings)
QUALIFYING_FILES=()
while IFS= read -r file; do
  [[ "$file" == .claude/* ]] || continue
  [[ "$file" == .claude/skills/sdd-*/learnings/*.json ]] && continue
  QUALIFYING_FILES+=("$file")
done <<< "$STAGED_FILES"

# No qualifying .claude/ files → nothing to check
if [[ ${#QUALIFYING_FILES[@]} -eq 0 ]]; then
  exit 0
fi

# Collect unique skills with changes (bash 3 compatible — no associative arrays)
CHANGED_SKILLS=""
for file in "${QUALIFYING_FILES[@]}"; do
  if [[ "$file" =~ ^\.claude/skills/(sdd-[^/]+)/ ]]; then
    skill="${BASH_REMATCH[1]}"
    # Dedup: only add if not already in the list
    if ! echo "$CHANGED_SKILLS" | grep -qx "$skill"; then
      CHANGED_SKILLS="${CHANGED_SKILLS}${CHANGED_SKILLS:+$'\n'}${skill}"
    fi
  fi
done

# Check each changed skill
if [[ -n "$CHANGED_SKILLS" ]]; then
  while IFS= read -r skill_name; do
    [[ -n "$skill_name" ]] || continue
    skill_file=".claude/skills/$skill_name/SKILL.md"

    # Skip deleted/renamed-away skills (SKILL.md removed or renamed to another skill)
    if git diff --cached --no-renames --diff-filter=D --name-only | grep -qx "$skill_file"; then
      continue
    fi

    # Check if SKILL.md is staged
    if ! echo "$STAGED_FILES" | grep -qx "$skill_file"; then
      ERRORS+=("Skill '$skill_name' has changed files but SKILL.md is not staged.")
      ERRORS+=("  Fix: .claude/scripts/sdd-bump-version.sh skill $skill_name patch && git add $skill_file")
      continue
    fi

    # For new files (no HEAD version), any version is fine
    head_version="$(git show HEAD:"$skill_file" 2>/dev/null | grep -m1 '^version:' | sed 's/^version:[[:space:]]*//' || echo "")"
    if [[ -z "$head_version" ]]; then
      continue
    fi

    # Compare staged version vs HEAD version
    staged_version="$(git diff --cached -- "$skill_file" | grep -m1 '^+version:' | sed 's/^+version:[[:space:]]*//' || echo "")"
    if [[ -z "$staged_version" ]]; then
      # version line wasn't changed in the diff — versions are equal
      ERRORS+=("Skill '$skill_name' version not bumped (still $head_version).")
      ERRORS+=("  Fix: .claude/scripts/sdd-bump-version.sh skill $skill_name patch && git add $skill_file")
    fi
  done <<< "$CHANGED_SKILLS"
fi

# Check project-level VERSION
head_proj="$(git show HEAD:"$VERSION_FILE" 2>/dev/null | tr -d '[:space:]' || echo "")"

if ! echo "$STAGED_FILES" | grep -qx "$VERSION_FILE"; then
  ERRORS+=("VERSION not staged but .claude/ files changed.")
  ERRORS+=("  Fix: .claude/scripts/sdd-bump-version.sh project patch && git add VERSION")
elif [[ -n "$head_proj" ]]; then
  staged_proj="$(git diff --cached -- "$VERSION_FILE" | grep '^+' | grep -v '^+++' | head -1 | sed 's/^+//' | tr -d '[:space:]' || echo "")"
  if [[ -z "$staged_proj" ]]; then
    ERRORS+=("VERSION not bumped (still $head_proj).")
    ERRORS+=("  Fix: .claude/scripts/sdd-bump-version.sh project patch && git add VERSION")
  fi
fi

# Check CHANGELOG.md is staged when VERSION is bumped
if echo "$STAGED_FILES" | grep -qx "$VERSION_FILE"; then
  if ! echo "$STAGED_FILES" | grep -qx "CHANGELOG.md"; then
    ERRORS+=("CHANGELOG.md not staged but VERSION was bumped.")
    ERRORS+=("  Fix: .claude/scripts/sdd-bump-version.sh auto (includes changelog update)")
  else
    # Check that CHANGELOG.md actually has a new entry (not just the old content)
    changelog_diff="$(git diff --cached -- CHANGELOG.md | grep '^+##' | grep -v '^+++' || true)"
    if [[ -z "$changelog_diff" ]]; then
      ERRORS+=("CHANGELOG.md is staged but has no new version entry.")
      ERRORS+=("  Fix: Add a ## [x.y.z] entry to CHANGELOG.md, or run: .claude/scripts/sdd-bump-version.sh auto")
    fi
  fi
fi

# Report
if [[ ${#ERRORS[@]} -gt 0 ]]; then
  echo ""
  echo "╔══════════════════════════════════════════════════════╗"
  echo "║  SDD Version Check Failed                           ║"
  echo "╠══════════════════════════════════════════════════════╣"
  for err in "${ERRORS[@]}"; do
    echo "║  $err"
  done
  echo "║"
  echo "║  Quick fix: .claude/scripts/sdd-bump-version.sh auto"
  echo "╚══════════════════════════════════════════════════════╝"
  echo ""
  exit 1
fi

exit 0
