#!/usr/bin/env bash
# Container utility functions for Proxmox deployment
# Standardized functions for container operations

# Start container and wait for it to be ready
# Returns 0 on success, 1 on failure
start_container_and_wait() {
    local vmid="$1"
    local max_wait="${2:-30}"
    
    log_info "Starting container $vmid..."
    local start_output
    start_output=$(pct start "$vmid" 2>&1) || {
        log_warn "Container $vmid failed to start"
        log_info "Startup output: $start_output"
        
        # Check current status
        local status
        status=$(pct status "$vmid" 2>/dev/null | awk '{print $2}' || echo "unknown")
        log_warn "Container $vmid status: $status"
        
        # If already running, that's fine
        if [[ "$status" == "running" ]]; then
            log_info "Container $vmid is already running"
        else
            log_error "Container $vmid is not running. Checking configuration..."
            log_info "Container configuration:"
            pct config "$vmid" 2>&1 | head -30 || true
            log_error "Cannot proceed - container not running"
            log_info "Try manually: pct start $vmid"
            log_info "Check logs: journalctl -u pve-container@$vmid"
            return 1
        fi
    }
    
    # Wait for container to be fully started and ready for operations
    log_info "Waiting for container $vmid to be fully ready..."
    local waited=0
    while [[ $waited -lt $max_wait ]]; do
        # Check if container is running and responsive
                if pct exec "$vmid" -- test -f /etc/os-release 2>/dev/null; then
            log_success "Container $vmid is ready"
            return 0
        fi
        sleep 1
        waited=$((waited + 1))
    done
    
    if [[ $waited -ge $max_wait ]]; then
        log_warn "Container $vmid may not be fully ready, but proceeding..."
        # Check if at least running
        local status
        status=$(pct status "$vmid" 2>/dev/null | awk '{print $2}' || echo "unknown")
        if [[ "$status" != "running" ]]; then
            log_error "Container $vmid is not running after wait period"
            return 1
        fi
    fi
    
    return 0
}

# Verify container is ready for file operations
verify_container_ready() {
    local vmid="$1"
    
    local status
    status=$(pct status "$vmid" 2>/dev/null | awk '{print $2}' || echo "unknown")
    
    if [[ "$status" != "running" ]]; then
        log_error "Container $vmid is not running (status: $status)"
        return 1
    fi
    
    # Try a simple command to verify responsiveness
    if ! pct exec "$vmid" -- test -d / 2>/dev/null; then
        log_error "Container $vmid is not responsive"
        return 1
    fi
    
    return 0
}

