#!/usr/bin/env bash
# Progress Tracking Utilities
# Provides functions for tracking deployment progress with ETA

# Initialize progress tracking
# Usage: init_progress_tracking total_steps "step_name"
init_progress_tracking() {
    local total="$1"
    local step_name="${2:-Step}"
    export PROGRESS_TOTAL="$total"
    export PROGRESS_CURRENT=0
    export PROGRESS_STEP_NAME="$step_name"
    export PROGRESS_START_TIME=$(date +%s)
}

# Update progress
# Usage: update_progress current_step "substep_name"
update_progress() {
    local current="$1"
    local substep="${2:-}"
    export PROGRESS_CURRENT="$current"
    local percent=$((current * 100 / PROGRESS_TOTAL))
    local elapsed=$(($(date +%s) - PROGRESS_START_TIME))
    local eta=0
    if [[ $current -gt 0 ]]; then
        eta=$((elapsed * (PROGRESS_TOTAL - current) / current))
    fi
    
    local eta_str=""
    if [[ $eta -gt 0 ]]; then
        local eta_min=$((eta / 60))
        local eta_sec=$((eta % 60))
        eta_str="ETA: ${eta_min}m ${eta_sec}s"
    fi
    
    local progress_bar=""
    local bar_width=40
    local filled=$((percent * bar_width / 100))
    for ((i=0; i<filled; i++)); do
        progress_bar+="█"
    done
    for ((i=filled; i<bar_width; i++)); do
        progress_bar+="░"
    done
    
    if [[ -n "$substep" ]]; then
        log_info "Progress: [$percent%] [$progress_bar] [$current/$PROGRESS_TOTAL] $substep $eta_str"
    else
        log_info "Progress: [$percent%] [$progress_bar] [$current/$PROGRESS_TOTAL] $eta_str"
    fi
}

# Complete progress tracking
complete_progress() {
    local elapsed=$(($(date +%s) - PROGRESS_START_TIME))
    local elapsed_min=$((elapsed / 60))
    local elapsed_sec=$((elapsed % 60))
    update_progress "$PROGRESS_TOTAL" "Complete"
    log_success "$PROGRESS_STEP_NAME completed in ${elapsed_min}m ${elapsed_sec}s"
    
    # Cleanup
    unset PROGRESS_TOTAL PROGRESS_CURRENT PROGRESS_STEP_NAME PROGRESS_START_TIME
}

# Track parallel execution progress
# Usage: track_parallel_progress total current
track_parallel_progress() {
    local total="$1"
    local current="$2"
    local percent=$((current * 100 / total))
    local elapsed=$(($(date +%s -d "@${PROGRESS_START_TIME:-$(date +%s)}")))
    local eta=0
    if [[ $current -gt 0 ]]; then
        eta=$((elapsed * (total - current) / current))
    fi
    
    log_info "[$current/$total] Completed ($percent%) ETA: ${eta}s"
}

