#!/bin/bash
#
# Install Git Hooks Script
#
# This script installs the pre-commit hook that enforces
# 100% unit test passing before commits.
#
# Usage:
#   ./install-hooks.sh

set -e

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

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}📦 Installing Git Hooks${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)

if [ -z "$GIT_ROOT" ]; then
    echo -e "${YELLOW}⚠️  WARNING: Not in a git repository${NC}"
    echo -e "${YELLOW}   Please run this script from within the git repository.${NC}"
    exit 1
fi

# Determine backend directory
BACKEND_DIR="$GIT_ROOT/backend"
HOOKS_SOURCE="$BACKEND_DIR/.git-hooks"
HOOKS_DEST="$GIT_ROOT/.git/hooks"

if [ ! -d "$BACKEND_DIR" ]; then
    echo -e "${YELLOW}⚠️  WARNING: Backend directory not found${NC}"
    exit 1
fi

if [ ! -d "$HOOKS_SOURCE" ]; then
    echo -e "${YELLOW}⚠️  WARNING: .git-hooks directory not found${NC}"
    exit 1
fi

# Install pre-commit hook
echo -e "${YELLOW}Installing pre-commit hook...${NC}"

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

cp "$HOOKS_SOURCE/pre-commit" "$HOOKS_DEST/pre-commit"
chmod +x "$HOOKS_DEST/pre-commit"

echo -e "${GREEN}✅ Pre-commit hook installed successfully!${NC}"
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}What happens now:${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "✅ Unit tests will run automatically before each commit"
echo -e "✅ Commits will be blocked if tests fail"
echo -e "✅ You'll see clear error messages if tests fail"
echo ""
echo -e "${YELLOW}To bypass the hook (WIP commits only):${NC}"
echo -e "  git commit --no-verify"
echo ""
echo -e "${YELLOW}To uninstall:${NC}"
echo -e "  rm $HOOKS_DEST/pre-commit"
echo ""
echo -e "${GREEN}Happy coding! 🚀${NC}"
echo ""
