#!/bin/bash

# Combined Git Hook Management Script for research
# This script can install or remove pre-commit hooks for this repository
# Auto-generated by git-shell-hook.ts

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

# Configuration
SCRIPT_URL="https://memo.d.foundation/tools/ci-lint.js"
HOOK_TYPE="pre-commit"
REPO_NAME="research"

# Function to show usage
show_usage() {
    echo "Usage: $0 [install|remove|status]"
    echo ""
    echo "Commands:"
    echo "  install  - Install pre-commit hook"
    echo "  remove   - Remove pre-commit hook"
    echo "  status   - Show hook status"
    echo ""
    echo "Examples:"
    echo "  $0 install"
    echo "  $0 remove"
    echo "  $0 status"
}

# Function to get git directory (handles worktrees and submodules)
get_git_dir() {
    local repo_path="$1"
    local git_path="${repo_path}/.git"
    
    if [ ! -e "$git_path" ]; then
        return 1
    fi
    
    if [ -d "$git_path" ]; then
        # Regular git repository
        echo "$git_path"
    elif [ -f "$git_path" ]; then
        # Git worktree or submodule - read the gitdir reference
        local git_dir=$(grep "^gitdir:" "$git_path" | cut -d' ' -f2-)
        if [[ "$git_dir" = /* ]]; then
            # Absolute path
            echo "$git_dir"
        else
            # Relative path
            echo "$(cd "$repo_path" && cd "$git_dir" && pwd)"
        fi
    else
        return 1
    fi
}

# Function to install hook
install_hook() {
    echo "🔧 Installing ${HOOK_TYPE} hook for ${REPO_NAME}..."
    
    # Check if we're in a git repository
    if [ ! -d ".git" ] && [ ! -f ".git" ]; then
        echo -e "${RED}❌ Error: Not in a git repository root directory${NC}"
        echo "Please run this script from the root of the ${REPO_NAME} repository"
        exit 1
    fi

    echo -e "${BLUE}📋 Hook Configuration:${NC}"
    echo "   Repository: ${REPO_NAME}"
    echo "   Script URL: ${SCRIPT_URL}"
    echo "   Hook Type: ${HOOK_TYPE}"
    echo ""

    # Get the actual git directory
    GIT_DIR=$(get_git_dir ".")
    if [ -z "$GIT_DIR" ]; then
        echo -e "${RED}❌ Error: Could not determine git directory${NC}"
        exit 1
    fi

    HOOKS_DIR="${GIT_DIR}/hooks"
    HOOK_PATH="${HOOKS_DIR}/${HOOK_TYPE}"

    echo "📁 Git directory: ${GIT_DIR}"
    echo "🪝 Hook path: ${HOOK_PATH}"
    echo ""

    # Create hooks directory if it doesn't exist
    if [ ! -d "$HOOKS_DIR" ]; then
        echo "📁 Creating hooks directory..."
        mkdir -p "$HOOKS_DIR"
    fi

    # Create the hook script
    echo "📝 Creating ${HOOK_TYPE} hook..."

    cat > "$HOOK_PATH" << 'EOF'
#!/bin/bash

# Auto-generated git hook for research
# This hook fetches and executes a script from: https://memo.d.foundation/tools/ci-lint.js

set -e

echo "Running pre-commit hook for research..."
echo "Fetching script from: https://memo.d.foundation/tools/ci-lint.js"

# Create temporary file for the script
TEMP_SCRIPT=$(mktemp)
trap 'rm -f "$TEMP_SCRIPT"' EXIT

# Fetch the script using curl (fallback to wget if curl not available)
if command -v curl >/dev/null 2>&1; then
    if ! curl -sSL "https://memo.d.foundation/tools/ci-lint.js" -o "$TEMP_SCRIPT"; then
        echo "Error: Failed to fetch script using curl"
        exit 1
    fi
elif command -v wget >/dev/null 2>&1; then
    if ! wget -q "https://memo.d.foundation/tools/ci-lint.js" -O "$TEMP_SCRIPT"; then
        echo "Error: Failed to fetch script using wget"
        exit 1
    fi
else
    echo "Error: Neither curl nor wget is available"
    exit 1
fi

# Check if the script was downloaded successfully
if [ ! -s "$TEMP_SCRIPT" ]; then
    echo "Error: Downloaded script is empty"
    exit 1
fi

# Execute the script with Node.js if it's a TypeScript/JavaScript file
if [[ "https://memo.d.foundation/tools/ci-lint.js" == *.ts ]] || [[ "https://memo.d.foundation/tools/ci-lint.js" == *.js ]]; then
    # Check if we're in a Node.js project directory
    if [ -f "package.json" ] || [ -f "tsconfig.json" ]; then
        # Try to use tsx for TypeScript files, fallback to node
        if [[ "https://memo.d.foundation/tools/ci-lint.js" == *.ts ]] && command -v tsx >/dev/null 2>&1; then
            echo "Executing TypeScript script with tsx..."
            tsx "$TEMP_SCRIPT"
        elif command -v node >/dev/null 2>&1; then
            echo "Executing script with node..."
            node "$TEMP_SCRIPT"
        else
            echo "Error: Node.js not found"
            exit 1
        fi
    else
        echo "Warning: Not in a Node.js project directory, but trying to execute anyway..."
        if command -v node >/dev/null 2>&1; then
            node "$TEMP_SCRIPT"
        else
            echo "Error: Node.js not found"
            exit 1
        fi
    fi
else
    # For other script types, make executable and run directly
    chmod +x "$TEMP_SCRIPT"
    "$TEMP_SCRIPT"
fi

echo "pre-commit hook completed successfully for research"
EOF

    # Make the hook executable
    chmod +x "$HOOK_PATH"

    echo -e "${GREEN}✅ Successfully installed ${HOOK_TYPE} hook!${NC}"
    show_status
}

# Function to remove hook
remove_hook() {
    echo "🗑️ Removing ${HOOK_TYPE} hook for ${REPO_NAME}..."
    
    # Check if we're in a git repository
    if [ ! -d ".git" ] && [ ! -f ".git" ]; then
        echo -e "${RED}❌ Error: Not in a git repository root directory${NC}"
        exit 1
    fi

    # Get the actual git directory
    GIT_DIR=$(get_git_dir ".")
    if [ -z "$GIT_DIR" ]; then
        echo -e "${RED}❌ Error: Could not determine git directory${NC}"
        exit 1
    fi

    HOOKS_DIR="${GIT_DIR}/hooks"
    HOOK_PATH="${HOOKS_DIR}/${HOOK_TYPE}"

    echo "📁 Git directory: ${GIT_DIR}"
    echo "🪝 Hook path: ${HOOK_PATH}"
    echo ""

    # Remove the hook if it exists
    if [ -f "$HOOK_PATH" ]; then
        echo "🗑️ Removing ${HOOK_TYPE} hook..."
        rm -f "$HOOK_PATH"
        echo -e "${GREEN}✅ Successfully removed ${HOOK_TYPE} hook${NC}"
    else
        echo -e "${YELLOW}⚠ No ${HOOK_TYPE} hook found to remove${NC}"
    fi

    show_status
}

# Function to show hook status
show_status() {
    # Get the actual git directory
    GIT_DIR=$(get_git_dir ".")
    if [ -z "$GIT_DIR" ]; then
        echo -e "${RED}❌ Error: Could not determine git directory${NC}"
        exit 1
    fi

    HOOKS_DIR="${GIT_DIR}/hooks"
    HOOK_PATH="${HOOKS_DIR}/${HOOK_TYPE}"

    echo ""
    echo "📊 Hook Status for ${REPO_NAME}:"
    if [ -f "$HOOK_PATH" ]; then
        if [ -x "$HOOK_PATH" ]; then
            echo -e "   ✓ ${HOOK_TYPE} hook installed and executable"
        else
            echo -e "   ⚠ ${HOOK_TYPE} hook installed but not executable"
        fi
    else
        echo -e "   ✗ ${HOOK_TYPE} hook not installed"
    fi
    echo ""
}

# Main script logic
case "${1:-install}" in
    install)
        install_hook
        echo -e "${GREEN}🎉 Hook installation complete for ${REPO_NAME}!${NC}"
        echo ""
        echo "Available commands:"
        echo "  ./pre-commit-hook.sh install  - Reinstall hook"
        echo "  ./pre-commit-hook.sh remove   - Remove hook"
        echo "  ./pre-commit-hook.sh status   - Check hook status"
        echo ""
        echo "The hook will now run automatically on git ${HOOK_TYPE} operations."
        ;;
    remove)
        remove_hook
        echo -e "${GREEN}🎉 Hook removal complete for ${REPO_NAME}!${NC}"
        ;;
    status)
        show_status
        ;;
    *)
        echo -e "${RED}❌ Error: Unknown command '$1'${NC}"
        echo ""
        show_usage
        exit 1
        ;;
esac
