#!/bin/bash
# Codebase Indexer - Auto-Trigger Hook
# Runs automatically before sessions to detect and use codebase index

set -e

# Configuration
PROJECT_ROOT="$(pwd)"
INDEX_FILE="$PROJECT_ROOT/.codebase-index.json"
LOG_FILE="$HOME/.claude/logs/codebase-indexer.log"
AUTO_UPDATE="${AUTO_UPDATE:-true}"

# Create log directory
mkdir -p "$(dirname "$LOG_FILE")"

# Logging
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# Check if project has an index
check_index() {
    if [ -f "$INDEX_FILE" ]; then
        # Index exists - check if it needs updating
        if [ "$AUTO_UPDATE" = "true" ]; then
            # Check git for changes
            if git -C "$PROJECT_ROOT" rev-parse --git-dir > /dev/null 2>&1; then
                local changes=$(git -C "$PROJECT_ROOT" diff --name-only HEAD 2>/dev/null | wc -l)
                if [ $changes -gt 0 ]; then
                    log "Changes detected ($changes files), updating index..."
                    bash "$HOME/.claude/skills/codebase-indexer/update-index.sh" "$PROJECT_ROOT" > /dev/null 2>&1 &
                fi
            fi
        fi

        # Export index info for Claude
        export CODEBASE_INDEX_EXISTS="true"
        export CODEBASE_INDEX_PATH="$INDEX_FILE"
        log "Index found at $INDEX_FILE"
        return 0
    fi

    # No index - check if this is a code project
    if is_code_project "$PROJECT_ROOT"; then
        log "Code project detected but no index found"
        export CODEBASE_INDEX_SUGGEST="true"
    fi

    return 1
}

# Check if directory is a code project
is_code_project() {
    local dir="$1"

    # Check for common code project indicators
    [ -f "$dir/package.json" ] && return 0
    [ -f "$dir/tsconfig.json" ] && return 0
    [ -f "$dir/pyproject.toml" ] && return 0
    [ -f "$dir/requirements.txt" ] && return 0
    [ -f "$dir/go.mod" ] && return 0
    [ -f "$dir/Cargo.toml" ] && return 0
    [ -f "$dir/pom.xml" ] && return 0
    [ -d "$dir/src" ] && return 0
    [ -d "$dir/lib" ] && return 0

    # Check for code files
    local code_files=$(find "$dir" -maxdepth 2 -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" -o -name "*.rs" \) 2>/dev/null | wc -l)
    [ $code_files -gt 5 ] && return 0

    return 1
}

# Main function
main() {
    check_index
}

main
