#!/bin/bash
#
# Install documentation sync git hooks
#

PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"

if [ -z "$PROJECT_ROOT" ]; then
    echo "Error: Not in a git repository"
    exit 1
fi

DOC_SYNC_DIR="$PROJECT_ROOT/.dss/doc-sync"
GIT_HOOKS_DIR="$PROJECT_ROOT/.git/hooks"

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

echo "🔧 Installing documentation sync git hooks..."
echo ""

# Check if doc-sync hooks exist
if [ ! -f "$DOC_SYNC_DIR/hooks/pre-commit" ]; then
    echo "Error: Doc-sync hooks not found in $DOC_SYNC_DIR/hooks/"
    exit 1
fi

# Install pre-commit hook
echo "Installing pre-commit hook..."
if [ -f "$GIT_HOOKS_DIR/pre-commit" ]; then
    echo -e "${YELLOW}⚠️  Existing pre-commit hook found${NC}"
    echo "Backing up to pre-commit.backup"
    mv "$GIT_HOOKS_DIR/pre-commit" "$GIT_HOOKS_DIR/pre-commit.backup"
fi

cp "$DOC_SYNC_DIR/hooks/pre-commit" "$GIT_HOOKS_DIR/pre-commit"
chmod +x "$GIT_HOOKS_DIR/pre-commit"
echo -e "${GREEN}✓ pre-commit hook installed${NC}"

# Install post-commit hook
echo "Installing post-commit hook..."
if [ -f "$GIT_HOOKS_DIR/post-commit" ]; then
    echo -e "${YELLOW}⚠️  Existing post-commit hook found${NC}"
    echo "Backing up to post-commit.backup"
    mv "$GIT_HOOKS_DIR/post-commit" "$GIT_HOOKS_DIR/post-commit.backup"
fi

cp "$DOC_SYNC_DIR/hooks/post-commit" "$GIT_HOOKS_DIR/post-commit"
chmod +x "$GIT_HOOKS_DIR/post-commit"
echo -e "${GREEN}✓ post-commit hook installed${NC}"

echo ""
echo -e "${GREEN}✅ Git hooks installed successfully${NC}"
echo ""
echo "Hooks installed:"
echo "  - pre-commit: Validates manifest and warns about doc changes"
echo "  - post-commit: Regenerates documentation automatically"
echo ""
echo "To uninstall, remove the hooks from .git/hooks/"
