#!/bin/bash
# Tempo shell hook for automatic project tracking
# This script should be sourced in your shell profile (.bashrc, .zshrc, etc.)

# Configuration
TEMPO_BIN="${TEMPO_BIN:-tempo}"
TEMPO_DEBUG="${TEMPO_DEBUG:-0}"
TEMPO_HOOK_ENABLED="${TEMPO_HOOK_ENABLED:-1}"

# Internal variables
_TEMPO_LAST_DIR=""
_TEMPO_CLIENT_PATH=""

# Debug logging function
_tempo_debug() {
    if [[ "$TEMPO_DEBUG" == "1" ]]; then
        echo "[TEMPO DEBUG] $*" >&2
    fi
}

# Function to detect if a directory is a project
_tempo_is_project() {
    local dir="$1"
    
    # Check for git repository
    if [[ -d "$dir/.git" ]]; then
        return 0
    fi
    
    # Check for .tempo marker
    if [[ -f "$dir/.tempo" ]]; then
        return 0
    fi
    
    # Check for common project files
    if [[ -f "$dir/package.json" ]] || \
       [[ -f "$dir/Cargo.toml" ]] || \
       [[ -f "$dir/pyproject.toml" ]] || \
       [[ -f "$dir/pom.xml" ]] || \
       [[ -f "$dir/Makefile" ]] || \
       [[ -f "$dir/CMakeLists.txt" ]] || \
       [[ -f "$dir/go.mod" ]] || \
       [[ -f "$dir/composer.json" ]]; then
        return 0
    fi
    
    return 1
}

# Function to find the project root
_tempo_find_project_root() {
    local dir="$1"
    local original_dir="$dir"
    
    # Walk up the directory tree
    while [[ "$dir" != "/" ]]; do
        if _tempo_is_project "$dir"; then
            echo "$dir"
            return 0
        fi
        dir=$(dirname "$dir")
    done
    
    # If no project found, return the original directory if it's a reasonable project
    if [[ -w "$original_dir" ]] && [[ ! "$original_dir" =~ ^/(usr|bin|lib|etc|var|tmp|proc|sys|dev) ]]; then
        echo "$original_dir"
        return 0
    fi
    
    return 1
}

# Function to send IPC message to tempo daemon
_tempo_send_ipc() {
    local socket_path="${HOME}/.tempo/daemon.sock"
    
    # Simple check if socket exists
    if [[ ! -S "$socket_path" ]]; then
        _tempo_debug "Daemon socket not found at $socket_path"
        return 1
    fi
    
    # Use the tempo CLI as IPC client
    if command -v "$TEMPO_BIN" >/dev/null 2>&1; then
        "$TEMPO_BIN" "$@" 2>/dev/null
    else
        _tempo_debug "tempo binary not found in PATH"
        return 1
    fi
}

# Function to handle directory change
_tempo_on_directory_change() {
    if [[ "$TEMPO_HOOK_ENABLED" != "1" ]]; then
        return
    fi
    
    local current_dir="$PWD"
    
    # Skip if we're in the same directory
    if [[ "$current_dir" == "$_TEMPO_LAST_DIR" ]]; then
        return
    fi
    
    _tempo_debug "Directory changed from '$_TEMPO_LAST_DIR' to '$current_dir'"
    
    # Find project root
    local project_root
    if project_root=$(_tempo_find_project_root "$current_dir"); then
        _tempo_debug "Found project at: $project_root"
        
        # Send project entered signal via CLI
        _tempo_send_ipc session start --project "$project_root" --context terminal
        
        # Export for other tools
        export TEMPO_CURRENT_PROJECT="$project_root"
    else
        _tempo_debug "No project found for: $current_dir"
        unset TEMPO_CURRENT_PROJECT
    fi
    
    _TEMPO_LAST_DIR="$current_dir"
}

# Function to handle shell exit
_tempo_on_shell_exit() {
    if [[ "$TEMPO_HOOK_ENABLED" == "1" ]] && [[ -n "$TEMPO_CURRENT_PROJECT" ]]; then
        _tempo_debug "Shell exiting, leaving project: $TEMPO_CURRENT_PROJECT"
        _tempo_send_ipc session stop
    fi
}

# Bash-specific hooks
if [[ "$SHELL" =~ bash ]]; then
    # Override cd command
    cd() {
        builtin cd "$@"
        local result=$?
        _tempo_on_directory_change
        return $result
    }
    
    # Hook into prompt command
    if [[ -z "$PROMPT_COMMAND" ]]; then
        PROMPT_COMMAND="_tempo_on_directory_change"
    else
        PROMPT_COMMAND="$PROMPT_COMMAND; _tempo_on_directory_change"
    fi
    
    # Handle shell exit
    trap '_tempo_on_shell_exit' EXIT

# Zsh-specific hooks  
elif [[ "$SHELL" =~ zsh ]]; then
    # Use chpwd hook for directory changes
    chpwd_functions+=(_tempo_on_directory_change)
    
    # Override cd command as backup
    cd() {
        builtin cd "$@"
        local result=$?
        _tempo_on_directory_change
        return $result
    }
    
    # Handle shell exit
    zshexit() {
        _tempo_on_shell_exit
    }
fi

# Initialize for current directory
_tempo_on_directory_change

# Utility functions for manual control
tempo-enable() {
    export TEMPO_HOOK_ENABLED=1
    echo "✅ Tempo automatic tracking enabled"
    _tempo_on_directory_change
}

tempo-disable() {
    export TEMPO_HOOK_ENABLED=0
    echo "⏸️ Tempo automatic tracking disabled"
}

tempo-status() {
    if [[ "$TEMPO_HOOK_ENABLED" == "1" ]]; then
        echo "✅ Tempo automatic tracking is enabled"
        if [[ -n "$TEMPO_CURRENT_PROJECT" ]]; then
            echo "   📂 Current project: $TEMPO_CURRENT_PROJECT"
        else
            echo "   💤 No active project"
        fi
    else
        echo "⏸️ Tempo automatic tracking is disabled"
    fi
    
    # Show daemon status
    if command -v "$TEMPO_BIN" >/dev/null 2>&1; then
        echo ""
        "$TEMPO_BIN" status
    fi
}

tempo-debug() {
    if [[ "$TEMPO_DEBUG" == "1" ]]; then
        export TEMPO_DEBUG=0
        echo "🔇 Tempo debug logging disabled"
    else
        export TEMPO_DEBUG=1
        echo "🔊 Tempo debug logging enabled"
    fi
}

# Print installation message
if [[ "$TEMPO_DEBUG" == "1" ]]; then
    echo "🔄 Tempo shell hook loaded (debug mode)"
fi