#!/bin/bash
# Install Git Hooks for DDD Architectural Health + Test Suites
#
# Usage: ./scripts/install-hooks.sh [--with-tests]
#
# Options:
#   --with-tests    Install pre-push hook with full test suite (recommended)
#   (default)       Install pre-commit hook only (fast architecture checks)
#
# Works with both regular repos and worktrees.

set -e

INSTALL_TESTS=false
if [ "$1" = "--with-tests" ]; then
    INSTALL_TESTS=true
fi

echo "🔧 Installing DDD Architectural Health Hooks"
echo "============================================="
echo ""

# Detect git directory (handles worktrees)
if [ -f .git ]; then
    # Worktree: .git is a file pointing to actual git dir
    GIT_DIR=$(cat .git | sed 's/gitdir: //')
    HOOKS_DIR="$GIT_DIR/hooks"
else
    # Regular repo: .git is a directory
    HOOKS_DIR=".git/hooks"
fi

echo "Git hooks directory: $HOOKS_DIR"

# Create hooks directory if it doesn't exist
mkdir -p "$HOOKS_DIR"

# Install pre-commit hook (fast - architecture only)
echo "📝 Installing pre-commit hook (fast checks)..."
if [ -f ".git-hooks/pre-commit" ]; then
    cp .git-hooks/pre-commit "$HOOKS_DIR/pre-commit"
    chmod +x "$HOOKS_DIR/pre-commit"
    echo "✅ Pre-commit installed from .git-hooks/"
else
    # Fallback: create inline
    cat > "$HOOKS_DIR/pre-commit" << 'EOF'
#!/bin/bash
# Pre-commit hook: DDD Architectural Health Validation
# Runs validation scripts before allowing commit
#
# To skip: git commit --no-verify (use sparingly!)

set -e

echo "🔍 Running DDD Architectural Health Checks..."
echo "=============================================="
echo ""

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

FAILED=0

# Check 1: DDD Import Validator
echo "📦 Validating cross-domain imports..."
if ./scripts/validate-ddd-imports.sh > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Import validation passed"
else
    echo -e "${RED}✗${NC} Import validation failed"
    echo ""
    echo "Run './scripts/validate-ddd-imports.sh' to see details"
    FAILED=1
fi

# Check 2: DDD Boundary Enforcement
echo "🚧 Checking bounded context boundaries..."
if ./scripts/enforce-ddd-boundaries.sh > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} No boundary violations"
else
    echo -e "${RED}✗${NC} Boundary violations detected"
    echo ""
    echo "Run './scripts/enforce-ddd-boundaries.sh' to see details"
    FAILED=1
fi

# Check 3: God Object Detection (warning only, doesn't fail)
echo "👹 Checking for god objects..."
./scripts/detect-god-objects.sh > /dev/null 2>&1
echo -e "${GREEN}✓${NC} God object check complete (warnings only)"

echo ""
echo "=============================================="

if [ $FAILED -eq 1 ]; then
    echo -e "${RED}❌ Pre-commit checks FAILED${NC}"
    echo ""
    echo "Fix the issues above or use 'git commit --no-verify' to skip (not recommended)"
    exit 1
else
    echo -e "${GREEN}✅ All architectural health checks passed!${NC}"
    echo ""
    exit 0
fi
EOF
    chmod +x "$HOOKS_DIR/pre-commit"
    echo "✅ Pre-commit installed (inline)"
fi

# Optionally install pre-push hook (comprehensive - with tests)
if [ "$INSTALL_TESTS" = true ]; then
    echo ""
    echo "📝 Installing pre-push hook (full test suite)..."
    if [ -f ".git-hooks/pre-push" ]; then
        cp .git-hooks/pre-push "$HOOKS_DIR/pre-push"
        chmod +x "$HOOKS_DIR/pre-push"
        echo "✅ Pre-push installed from .git-hooks/"
    else
        echo "⚠️  .git-hooks/pre-push not found, skipping"
    fi
fi

# Configure git to use the hooks directory (especially important for worktrees)
echo ""
echo "🔧 Configuring Git to use hooks..."
git config core.hooksPath "$HOOKS_DIR"

echo ""
echo "✅ Installation Complete!"
echo ""
echo "📋 What's installed:"
echo "  ✓ Pre-commit hook (fast - <10s)"
echo "    - DDD import validation"
echo "    - Boundary enforcement"
echo "    - God object detection"
if [ "$INSTALL_TESTS" = true ]; then
    echo "  ✓ Pre-push hook (comprehensive - ~5min)"
    echo "    - All architecture checks"
    echo "    - Unit tests"
    echo "    - Integration tests"
    echo "    - E2E tests (critical paths)"
fi
echo ""
echo "📋 Usage:"
echo "  • git commit    → runs pre-commit (fast)"
if [ "$INSTALL_TESTS" = true ]; then
    echo "  • git push      → runs pre-push (comprehensive)"
fi
echo "  • --no-verify   → skips hooks (emergency only)"
echo ""
echo "📋 To uninstall:"
echo "  git config --unset core.hooksPath"
echo "  rm $HOOKS_DIR/pre-commit"
if [ "$INSTALL_TESTS" = true ]; then
    echo "  rm $HOOKS_DIR/pre-push"
fi
echo ""
echo "✨ Done! Try committing something to test it."
