#!/bin/bash

# TimeSafari Debug Hook Installer
# Run this script in any repository to install the debug pre-commit hook

set -e

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

echo -e "${BLUE}🔧 TimeSafari Debug Hook Installer${NC}"
echo "============================================="

# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo -e "${RED}❌ Error: Not in a git repository${NC}"
    echo "Please run this script from within a git repository"
    exit 1
fi

# Get repository root
REPO_ROOT=$(git rev-parse --show-toplevel)
HOOKS_DIR="$REPO_ROOT/.git/hooks"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${BLUE}Repository:${NC} $REPO_ROOT"
echo -e "${BLUE}Hooks directory:${NC} $HOOKS_DIR"
echo -e "${BLUE}Script directory:${NC} $SCRIPT_DIR"

# Check if hooks directory exists
if [[ ! -d "$HOOKS_DIR" ]]; then
    echo -e "${RED}❌ Error: Hooks directory not found${NC}"
    echo "This repository may not be properly initialized"
    exit 1
fi

# Check if we have the hook files in the repository
HOOK_SCRIPT="$SCRIPT_DIR/git-hooks/pre-commit"
CONFIG_FILE="$SCRIPT_DIR/git-hooks/debug-checker.config"

if [[ ! -f "$HOOK_SCRIPT" ]]; then
    echo -e "${RED}❌ Error: Pre-commit hook script not found${NC}"
    echo "Expected location: $HOOK_SCRIPT"
    echo "Make sure you're running this from the TimeSafari repository"
    exit 1
fi

if [[ ! -f "$CONFIG_FILE" ]]; then
    echo -e "${RED}❌ Error: Debug checker config not found${NC}"
    echo "Expected location: $CONFIG_FILE"
    echo "Make sure you're running this from the TimeSafari repository"
    exit 1
fi

# Check if already installed
if [[ -f "$HOOKS_DIR/pre-commit" && -f "$HOOKS_DIR/debug-checker.config" ]]; then
    echo -e "${YELLOW}⚠️  Debug hook already appears to be installed${NC}"
    echo -e "   Checking if update is needed..."
    
    # Check if files are different
    if diff "$HOOK_SCRIPT" "$HOOKS_DIR/pre-commit" > /dev/null 2>&1; then
        echo -e "  ${GREEN}✅${NC} Hook script is up to date"
        HOOK_UP_TO_DATE=true
    else
        echo -e "  ${YELLOW}⚠️  Hook script differs - will update${NC}"
        HOOK_UP_TO_DATE=false
    fi
    
    if diff "$CONFIG_FILE" "$HOOKS_DIR/debug-checker.config" > /dev/null 2>&1; then
        echo -e "  ${GREEN}✅${NC} Config file is up to date"
        CONFIG_UP_TO_DATE=true
    else
        echo -e "  ${YELLOW}⚠️  Config file differs - will update${NC}"
        CONFIG_UP_TO_DATE=false
    fi
    
    if [[ "$HOOK_UP_TO_DATE" == true && "$CONFIG_UP_TO_DATE" == true ]]; then
        echo -e "\n${GREEN}✅ Debug hook is already up to date!${NC}"
        echo -e "   No installation needed"
    else
        echo -e "\n${BLUE}Updating existing installation...${NC}"
    fi
else
    echo -e "\n${BLUE}Installing debug hook...${NC}"
fi

# Copy/update the hook script if needed
if [[ "$HOOK_UP_TO_DATE" != true ]]; then
    cp "$HOOK_SCRIPT" "$HOOKS_DIR/pre-commit"
    chmod +x "$HOOKS_DIR/pre-commit"
    echo -e "  ${GREEN}✅${NC} Pre-commit hook installed/updated"
fi

# Copy/update the config file if needed
if [[ "$CONFIG_UP_TO_DATE" != true ]]; then
    cp "$CONFIG_FILE" "$HOOKS_DIR/debug-checker.config"
    echo -e "  ${GREEN}✅${NC} Configuration file installed/updated"
fi

# Copy/update the README if needed
README_FILE="$SCRIPT_DIR/git-hooks/README.md"
if [[ -f "$README_FILE" ]]; then
    if [[ ! -f "$HOOKS_DIR/README.md" ]] || ! diff "$README_FILE" "$HOOKS_DIR/README.md" > /dev/null 2>&1; then
        cp "$README_FILE" "$HOOKS_DIR/README.md"
        echo -e "  ${GREEN}✅${NC} Documentation installed/updated"
    else
        echo -e "  ${GREEN}✅${NC} Documentation is up to date"
    fi
fi

echo -e "\n${GREEN}🎉 Debug hook installation complete!${NC}"

# Test the installation
echo -e "\n${BLUE}Testing installation...${NC}"
if [[ -x "$HOOKS_DIR/pre-commit" ]]; then
    echo -e "  ${GREEN}✅${NC} Hook is executable"
else
    echo -e "  ${RED}❌${NC} Hook is not executable"
fi

if [[ -f "$HOOKS_DIR/debug-checker.config" ]]; then
    echo -e "  ${GREEN}✅${NC} Config file exists"
else
    echo -e "  ${RED}❌${NC} Config file missing"
fi

# Show current branch status
CURRENT_BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || echo "detached")
echo -e "\n${BLUE}Current branch:${NC} $CURRENT_BRANCH"

# Check if this is a protected branch
PROTECTED_BRANCHES=("master" "main" "production" "release" "stable")
IS_PROTECTED=false

for branch in "${PROTECTED_BRANCHES[@]}"; do
    if [[ "$CURRENT_BRANCH" == "$branch" ]]; then
        IS_PROTECTED=true
        break
    fi
done

if [[ "$IS_PROTECTED" == true ]]; then
    echo -e "${YELLOW}⚠️  You're on a protected branch ($CURRENT_BRANCH)${NC}"
    echo -e "   The debug hook will now run on all commits to this branch"
    echo -e "   Consider switching to a feature branch for development"
else
    echo -e "${GREEN}✅ You're on a feature branch ($CURRENT_BRANCH)${NC}"
    echo -e "   The debug hook will be skipped on this branch"
    echo -e "   You can develop with debug code freely"
fi

echo -e "\n${BLUE}Next steps:${NC}"
echo "1. The hook will now run automatically on protected branches"
echo "2. Test it by trying to commit a file with debug code"
echo "3. Use feature branches for development with debug code"
echo "4. Check the README.md in .git/hooks/ for more information"

echo -e "\n${BLUE}To test the hook:${NC}"
echo "1. Create a test file with debug code (e.g., console.log('test'))"
echo "2. Stage it: git add <filename>"
echo "3. Try to commit: git commit -m 'test'"
echo "4. The hook should prevent the commit if debug code is found"

echo -e "\n${BLUE}To uninstall:${NC}"
echo "rm $HOOKS_DIR/pre-commit"
echo "rm $HOOKS_DIR/debug-checker.config"
echo "rm $HOOKS_DIR/README.md"
