#!/bin/bash
#
# Post-commit hook for documentation synchronization
#
# Automatically regenerates documentation after commits

PROJECT_ROOT="$(git rev-parse --show-toplevel)"
DOC_SYNC_DIR="$PROJECT_ROOT/.dss/doc-sync"
RUNNER="$DOC_SYNC_DIR/doc_sync_runner.py"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo ""
echo "📚 Post-commit: Regenerating documentation..."

# Check if runner exists
if [ ! -f "$RUNNER" ]; then
    echo -e "${YELLOW}⚠️  Doc sync runner not found, skipping${NC}"
    exit 0
fi

# Get list of changed files in this commit
CHANGED_FILES=$(git diff-tree --no-commit-id --name-only -r HEAD)

# Check if any code files were changed
CODE_CHANGED=$(echo "$CHANGED_FILES" | grep -E "\.(py|js|ts|jsx|tsx)$")

if [ -z "$CODE_CHANGED" ]; then
    echo -e "${YELLOW}No code changes detected, skipping doc regeneration${NC}"
    exit 0
fi

# Run documentation generators
cd "$PROJECT_ROOT"
python3 "$RUNNER" run --trigger post-commit 2>&1

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Documentation updated successfully${NC}"

    # Check if .knowledge/ was updated
    KNOWLEDGE_UPDATED=$(git status --porcelain | grep "^.M .knowledge/")

    if [ -n "$KNOWLEDGE_UPDATED" ]; then
        echo ""
        echo -e "${YELLOW}📝 Knowledge base was updated:${NC}"
        echo "$KNOWLEDGE_UPDATED" | sed 's/^/  /'
        echo ""
        echo -e "${YELLOW}Stage and commit these changes:${NC}"
        echo "  git add .knowledge/"
        echo "  git commit -m \"docs: update knowledge base (auto-generated)\""
    fi
else
    echo -e "${YELLOW}⚠️  Documentation generation had warnings/errors${NC}"
    echo -e "${YELLOW}Check the output above for details${NC}"
fi

exit 0
