# Dotfiles Auto-Sync Configuration
# This file is sourced by shell configurations to enable automatic syncing

# Function to run dotfiles sync
dotfiles_sync() {
    if [[ -x "$HOME/.dotfiles/sync.sh" ]]; then
        "$HOME/.dotfiles/sync.sh" --background
    fi
}

# Function to enable/disable sync
dotfiles_sync_enable() {
    echo "true" > "$HOME/.dotfiles/.sync_enabled"
    echo "✅ Dotfiles auto-sync enabled"
}

dotfiles_sync_disable() {
    echo "false" > "$HOME/.dotfiles/.sync_enabled"
    echo "❌ Dotfiles auto-sync disabled"
}

# Function to manually trigger sync
dotfiles_sync_now() {
    if [[ -x "$HOME/.dotfiles/sync.sh" ]]; then
        "$HOME/.dotfiles/sync.sh" --manual
    else
        echo "❌ Sync script not found or not executable"
    fi
}

# Function to force sync (ignores timing)
dotfiles_sync_force() {
    if [[ -x "$HOME/.dotfiles/sync.sh" ]]; then
        "$HOME/.dotfiles/sync.sh" --force
    else
        echo "❌ Sync script not found or not executable"
    fi
}

# Function to show sync status
dotfiles_sync_status() {
    local sync_enabled_file="$HOME/.dotfiles/.sync_enabled"
    local last_sync_file="$HOME/.dotfiles/.last_sync"
    local sync_log="$HOME/.dotfiles/.sync.log"
    
    echo "🔧 Dotfiles Sync Status:"
    
    if [[ -f "$sync_enabled_file" ]]; then
        local enabled=$(cat "$sync_enabled_file")
        if [[ "$enabled" == "true" ]]; then
            echo "   Status: ✅ Enabled"
        else
            echo "   Status: ❌ Disabled"
        fi
    else
        echo "   Status: ✅ Enabled (default)"
    fi
    
    if [[ -f "$last_sync_file" ]]; then
        local last_sync=$(cat "$last_sync_file")
        local last_sync_date=$(date -d "@$last_sync" 2>/dev/null || echo "Unknown")
        echo "   Last sync: $last_sync_date"
    else
        echo "   Last sync: Never"
    fi
    
    if [[ -f "$sync_log" ]]; then
        echo "   Recent activity:"
        tail -3 "$sync_log" | sed 's/^/     /'
    fi
}

# Auto-sync on shell startup (only for interactive shells)
if [[ $- == *i* ]] && [[ -n "$HOME" ]] && [[ -d "$HOME/.dotfiles" ]]; then
    dotfiles_sync
    
    # Also check for updates periodically (background, no output)
    if [[ -f "$HOME/.dotfiles/lib/update_checker.sh" ]]; then
        (
            source "$HOME/.dotfiles/lib/update_checker.sh"
            check_for_updates false false >/dev/null 2>&1 &
        )
    fi
fi