#!/bin/bash

# Consolidated Worktree Environment Configuration
# Validates environment and configures shell commands for both bash and zsh as one cohesive operation
set -e

echo "🔧 Initializing consolidated worktree environment..."

# Environment variables are loaded by postCreate.sh and exported to child processes

# Note: This modifies shell profiles within the DevContainer environment only.
# The modifications are isolated to the container and do not affect the host system.

# Configure shell-specific worktree commands
configure_shell_worktree() {
    local shell="$1"
    local rc_file="$2"
    local marker="Git Worktree Management - Generated by worktree.sh init for $shell"
    
    echo "🐚 Configuring $shell worktree commands..."
    if ! grep -q "$marker" "$rc_file" 2>/dev/null; then
        echo "Adding worktree configuration to $shell profile..."
        # Only redirect stdout to RC file, let stderr go to terminal to avoid ANSI sequences in RC files
        if ./scripts/worktree/worktree.sh init --shell "$shell" >> "$rc_file"; then
            echo "✅ $shell worktree configuration added"
            return 0
        else
            echo "⚠️ Failed to initialize worktree for $shell"
            return 1
        fi
    else
        echo "✅ $shell worktree configuration already exists"
        return 0
    fi
}

# Validate environment and configure both shells as single operation
initialize_worktree_environment() {
    # Validation phase
    if [[ -z "$workingCopy" ]]; then
        echo "⚠️ Working copy path not set, skipping worktree initialization"
        return 1
    fi
    
    if [[ ! -d "$workingCopy" ]]; then
        echo "⚠️ Working copy directory not found: $workingCopy, skipping worktree initialization"
        return 1
    fi
    
    if [[ ! -f "$workingCopy/scripts/worktree/worktree.sh" ]]; then
        echo "ℹ️ Worktree scripts not present in this repository, skipping configuration"
        return 0  # Exit gracefully without error
    fi
    
    if [[ ! -x "$workingCopy/scripts/worktree/worktree.sh" ]]; then
        echo "⚠️ Worktree script found but not executable, skipping worktree initialization"
        return 1
    fi
    
    # Configuration phase - change to working copy once for all operations
    echo "📁 Entering working copy: $workingCopy"
    cd "$workingCopy"
    
    # Configure both shells as part of unified worktree initialization
    local bash_success=0
    local zsh_success=0
    
    configure_shell_worktree "bash" ~/.bashrc || bash_success=1
    configure_shell_worktree "zsh" ~/.zshrc || zsh_success=1
    
    cd - > /dev/null
    
    # Report consolidated results
    if [[ $bash_success -eq 0 && $zsh_success -eq 0 ]]; then
        echo "✅ Worktree environment fully configured for both shells"
        return 0
    elif [[ $bash_success -eq 0 || $zsh_success -eq 0 ]]; then
        echo "⚠️ Worktree environment partially configured (some shells failed)"
        return 0  # Partial success is acceptable
    else
        echo "❌ Worktree environment configuration failed"
        return 1
    fi
}

# Execute unified worktree initialization
initialize_worktree_environment || {
    exit_code=$?
    if [[ $exit_code -eq 0 ]]; then
        # Graceful skip - not an error
        exit 0
    else
        # Actual error occurred
        exit $exit_code
    fi
}