#!/bin/bash
#
# Helper functions for Calypso installer
#

# Check prerequisites
check_prerequisites() {
    log_info "Checking prerequisites..."
    
    # Check network connectivity
    if ! ping -c 1 -W 2 8.8.8.8 &>/dev/null; then
        log_warn "Network connectivity check failed. Some installations may fail."
    else
        log_info "✓ Network connectivity OK"
    fi
    
    # Check disk space (need at least 10GB free)
    AVAILABLE_SPACE=$(df -BG / | awk 'NR==2 {print $4}' | sed 's/G//')
    if [[ $AVAILABLE_SPACE -lt 10 ]]; then
        log_error "Insufficient disk space. Need at least 10GB, have ${AVAILABLE_SPACE}GB"
        exit 1
    else
        log_info "✓ Disk space OK (${AVAILABLE_SPACE}GB available)"
    fi
    
    # Check if already installed
    if [[ -d "$INSTALL_PREFIX/current" ]]; then
        log_warn "Calypso appears to be already installed at $INSTALL_PREFIX"
        read -p "Continue anyway? (y/N) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
    
    log_info "✓ Prerequisites check complete"
}

# Generate random string
generate_random_string() {
    local length=${1:-32}
    openssl rand -hex $((length / 2)) | head -c $length
}

# Generate JWT secret
generate_jwt_secret() {
    generate_random_string 64
}

# Generate database password
generate_db_password() {
    generate_random_string 32
}

# Wait for service
wait_for_service() {
    local service=$1
    local max_wait=${2:-30}
    local count=0
    
    while ! systemctl is-active --quiet "$service" && [[ $count -lt $max_wait ]]; do
        sleep 1
        ((count++))
    done
    
    if systemctl is-active --quiet "$service"; then
        return 0
    else
        return 1
    fi
}

# Check command exists
command_exists() {
    command -v "$1" &> /dev/null
}

# Get installed version
get_installed_version() {
    local command=$1
    if command_exists "$command"; then
        case $command in
            go)
                go version | awk '{print $3}' | sed 's/go//'
                ;;
            node)
                node --version | sed 's/v//'
                ;;
            psql)
                psql --version | awk '{print $3}'
                ;;
            *)
                "$command" --version 2>/dev/null | head -1
                ;;
        esac
    fi
}

# Print installation summary
print_installation_summary() {
    log_info ""
    log_info "=========================================="
    log_info "Installation Summary"
    log_info "=========================================="
    log_info ""
    log_info "Installation Paths:"
    log_info "  Binaries:     $INSTALL_PREFIX/releases/$CALYPSO_VERSION"
    log_info "  Configuration: $CONFIG_DIR"
    log_info "  Data:         $DATA_DIR"
    log_info "  Logs:         $LOG_DIR"
    log_info ""
    log_info "Services:"
    log_info "  calypso-api:  $(systemctl is-enabled calypso-api 2>/dev/null || echo 'not enabled')"
    log_info ""
    log_info "Default Credentials:"
    log_info "  Username: admin"
    log_info "  Password: $(cat /tmp/calypso_admin_password 2>/dev/null || echo 'Check installation log')"
    log_info ""
    log_info "Access:"
    log_info "  Web UI:      http://$(hostname -I | awk '{print $1}'):3000"
    log_info "  API:         http://$(hostname -I | awk '{print $1}'):8080"
    log_info ""
}

