#!/bin/bash

# GoodMem Server Reinstall Script
#
# This script handles server updates by checking for newer versions and performing
# a complete reinstallation when updates are available. It compares your local
# container version with the latest published version on GitHub Container Registry.
#
# Usage:
#   ~/.goodmem/reinstall.sh [OPTIONS]
#
# Options:
#   -c, --check-only    Only check for updates, don't reinstall
#   -f, --force         Skip confirmation prompts and force reinstall
#   -h, --help          Show this help message
#
# Examples:
#   ~/.goodmem/reinstall.sh --check-only          # Check if updates are available
#   ~/.goodmem/reinstall.sh                       # Interactive update (asks for confirmation)
#   ~/.goodmem/reinstall.sh --force               # Force update without prompts
#
# What this script does:
#   1. Analyzes your running goodmem-server container version and Git commit
#   2. Fetches latest version information from GitHub Container Registry
#   3. Compares RepoDigests to detect version changes (including version bumps)
#   4. If update available: stops container, removes old image, pulls latest, restarts
#   5. Provides detailed version information with digests and publication dates
#
# IMPORTANT - Data Safety:
#   - ONLY updates the goodmem-server container (preserves database container)
#   - Database data is NEVER touched - all your memories and data remain safe
#   - Database schema migrations are handled automatically by the server
#   - No risk of data loss during updates
#
# Version Detection Logic:
#   - Compares Docker image RepoDigests (most reliable for detecting changes)
#   - Handles version bumps where same Git commit gets new version tag
#   - Shows upgrade path (e.g., v1.0.100 → v1.0.101)
#   - Distinguishes between code changes and version-only bumps
#
# Prerequisites:
#   - GoodMem must be installed (docker-compose.yml exists in ~/.goodmem/)
#   - Docker and Docker Compose must be available
#   - User must have permissions to run docker commands
#   - curl must be available for GitHub API access

set -euo pipefail

# Configuration
readonly GOODMEM_DIR="$HOME/.goodmem"
readonly DOCKER_COMPOSE_FILE="$GOODMEM_DIR/docker-compose.yml"
readonly CONTAINER_NAME="goodmem-server"
readonly SERVICE_NAME="server"

# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m' # No Color

# Parse command line arguments
FORCE_MODE=false
CHECK_ONLY=false

show_help() {
    echo "GoodMem Server Reinstall Script"
    echo
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  -f, --force         Skip confirmation prompts"
    echo "  -c, --check-only    Only check for updates, don't reinstall"
    echo "  -h, --help          Show this help message"
    echo
    echo "This script will:"
    echo "  1. Check if a newer image version is available"
    echo "  2. Stop and remove the goodmem-server container (if update needed)"
    echo "  3. Remove the cached goodmem-server Docker image (if update needed)"
    echo "  4. Pull the latest image and restart the server (if update needed)"
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -f|--force)
                FORCE_MODE=true
                shift
                ;;
            -c|--check-only)
                CHECK_ONLY=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo -e "${RED}Error: Unknown option '$1'${NC}" >&2
                echo "Use --help for usage information." >&2
                exit 1
                ;;
        esac
    done
}

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

# Check if required tools are available
check_prerequisites() {
    log_info "Checking prerequisites..."

    # Check if docker is available
    if ! command -v docker &> /dev/null; then
        log_error "Docker is not installed or not in PATH"
        exit 1
    fi

    # Check if docker compose is available
    if ! docker compose version &> /dev/null; then
        log_error "Docker Compose is not available"
        log_error "Please ensure Docker Compose v2 is installed"
        exit 1
    fi

    # Check if GoodMem is installed
    if [[ ! -f "$DOCKER_COMPOSE_FILE" ]]; then
        log_error "GoodMem installation not found"
        log_error "Expected docker-compose.yml at: $DOCKER_COMPOSE_FILE"
        log_error "Please run the GoodMem installer first: curl -s https://get.goodmem.ai | bash"
        exit 1
    fi

    # Check if user can run docker commands
    if ! docker ps &> /dev/null; then
        log_error "Cannot run docker commands"
        log_error "Please ensure your user is in the docker group or run with sudo"
        exit 1
    fi

    # Check if curl is available
    if ! command -v curl &> /dev/null; then
        log_error "curl is not installed or not in PATH"
        log_error "Please install curl to check for updates from GitHub"
        exit 1
    fi

    log_success "All prerequisites met"
}

# Get the current image name from docker-compose.yml
get_image_name() {
    local image_name

    # Simplified approach: just get the image line and extract the value
    # Since you confirmed this command works, use it directly
    image_name=$(docker compose -f "$DOCKER_COMPOSE_FILE" config 2>/dev/null | \
                grep "image:" | \
                grep -v "^#" | \
                sed 's/.*image:[[:space:]]*//' | \
                head -1)

    if [[ -z "$image_name" ]]; then
        log_error "Could not determine image name from docker-compose.yml"
        log_error "Please check the server service configuration"
        log_error "Expected to find 'image:' under services.${SERVICE_NAME}"

        # Debug output
        log_info "Debug: docker compose config output:"
        docker compose -f "$DOCKER_COMPOSE_FILE" config 2>/dev/null | grep -A 5 -B 5 "image:" || echo "No image lines found"
        exit 1
    fi

    echo "$image_name"
}

# Get local image digest and ID
get_local_image_info() {
    local image_name="$1"
    local digest image_id

    # Get image ID
    image_id=$(docker images --format "{{.ID}}" "$image_name" 2>/dev/null | head -1)

    # Get RepoDigest from docker inspect (more reliable than docker images --digests)
    digest=$(docker inspect "$image_name" --format '{{index .RepoDigests 0}}' 2>/dev/null | sed 's/.*@//' || echo "")

    # If no RepoDigest, try the old method
    if [[ -z "$digest" || "$digest" == "<no value>" ]]; then
        digest=$(docker images --digests --format "{{.Digest}}" "$image_name" 2>/dev/null | head -1)
    fi

    echo "$digest|$image_id"
}

# Get specific version tags for a given digest from GitHub
lookup_version_by_digest() {
    # Since GitHub API is not accessible, we can't lookup versions by digest
    # This would require API access or web scraping
    echo "unknown"
}

# Get latest revision and version from GitHub by scraping the public page
get_latest_github_info() {
    local temp_file="/tmp/goodmem_versions.html"
    local versions_url="https://github.com/PAIR-Systems-Inc/goodmem/pkgs/container/goodmem%2Fserver/versions"

    # Download the GitHub packages page
    if curl -s -L "$versions_url" -o "$temp_file" 2>/dev/null; then
        local latest_sha latest_version

        # Get available versions sorted by version number (descending)
        local versions
        versions=$(grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' "$temp_file" 2>/dev/null | \
                  sort -V -r | uniq | head -10)

        if [[ -n "$versions" ]]; then
            # The first version is the highest version number (latest)
            latest_version=$(echo "$versions" | head -1)

            # Now try to find the SHA associated with this version
            # Look for patterns like: v1.0.101 followed by sha-... on the same line or nearby
            local version_pattern="$latest_version"

            # Search around the version for a SHA pattern
            # Method 1: Look for SHA near the version tag
            latest_sha=$(grep -A 5 -B 5 "$version_pattern" "$temp_file" 2>/dev/null | \
                        grep -oE 'sha-[a-f0-9]{40}' | head -1 | sed 's/sha-//')

            # Method 2: If that fails, try extracting the first SHA from the page (most recent entry)
            if [[ -z "$latest_sha" ]]; then
                latest_sha=$(grep -oE 'sha-[a-f0-9]{40}' "$temp_file" 2>/dev/null | head -1 | sed 's/sha-//')
            fi
        else
            # Fallback: get any version and SHA
            latest_version=$(grep -oE 'latest' "$temp_file" 2>/dev/null | head -1)
            latest_sha=$(grep -oE 'sha-[a-f0-9]{40}' "$temp_file" 2>/dev/null | head -1 | sed 's/sha-//')
        fi

        rm -f "$temp_file"

        # Return format: version|sha|versions_list
        local versions_list=""
        if [[ -n "$versions" ]]; then
            versions_list=$(echo "$versions" | tr '\n' ' ')
        fi

        # Try to extract the digest for the latest version using multiple methods
        local latest_digest=""

        # Extract the digest for the specific latest version using the proven working method
        if [[ -n "$latest_version" ]]; then
            # Look for digest within 20 lines after the version mention (same as debug script)
            latest_digest=$(grep -A 20 "$latest_version" "$temp_file" 2>/dev/null | \
                           grep -oE 'sha256:[a-f0-9]{64}' | head -1 | sed 's/sha256://')

            # If that fails, try looking within 20 lines before the version
            if [[ -z "$latest_digest" ]]; then
                latest_digest=$(grep -B 20 "$latest_version" "$temp_file" 2>/dev/null | \
                               grep -oE 'sha256:[a-f0-9]{64}' | tail -1 | sed 's/sha256://')
            fi
        fi

        # Final fallback: get the first digest from the page (most recent)
        if [[ -z "$latest_digest" ]]; then
            latest_digest=$(grep -oE 'sha256:[a-f0-9]{64}' "$temp_file" | head -1 | sed 's/sha256://')
        fi

        # Debug output
        if [[ -n "$latest_digest" ]]; then
            log_info "Successfully extracted digest for $latest_version: ${latest_digest:0:12}..."
        else
            local digest_count
            digest_count=$(grep -c 'sha256:' "$temp_file" 2>/dev/null || echo "0")
            log_info "Digest extraction failed for $latest_version (found $digest_count total patterns)"
        fi

        # Debug output to help troubleshoot (only show if we have values)
        if [[ -n "$latest_digest" && "$latest_digest" != "unknown" ]]; then
            log_info "Scraped from GitHub: version=$latest_version, sha=${latest_sha:0:12}..., digest=${latest_digest:0:12}..."
        else
            log_info "Scraped from GitHub: version=$latest_version, sha=${latest_sha:0:12}..., digest=not_found"
        fi

        echo "${latest_version:-unknown}|${latest_sha:-unknown}|$versions_list|${latest_digest:-unknown}"
        return 0
    fi

    rm -f "$temp_file"
    echo "unknown|unknown|"
    return 1
}

# Display available versions with digests and dates
show_available_versions_with_details() {
    local temp_file="$1"

    log_info "Recent versions with details:"

    if [[ ! -f "$temp_file" ]]; then
        log_info "  (No GitHub data available)"
        return 1
    fi

    # Get top 5 versions
    local versions
    versions=$(grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' "$temp_file" 2>/dev/null | \
              sort -V -r | uniq | head -5)

    if [[ -n "$versions" ]]; then
        while read -r version; do
            if [[ -n "$version" ]]; then
                # Get digest for this version
                local digest
                digest=$(grep -A 20 "$version" "$temp_file" 2>/dev/null | \
                         grep -oE 'sha256:[a-f0-9]{64}' | head -1 | sed 's/sha256://')

                # Get date for this version (look for "Published" near the version)
                local date_info
                date_info=$(grep -A 10 -B 10 "$version" "$temp_file" 2>/dev/null | \
                           grep -oE 'Published [^·]+' | head -1 | sed 's/Published //')

                # Format output
                local digest_short="${digest:0:12}..."
                if [[ -z "$digest" ]]; then
                    digest_short="unknown"
                fi

                if [[ -n "$date_info" ]]; then
                    log_info "  $version (${digest_short}) - $date_info"
                else
                    log_info "  $version (${digest_short})"
                fi
            fi
        done <<< "$versions"
    else
        log_info "  (Could not extract version information)"
    fi
}

# Get current version, revision, and RepoDigest from running container
identify_local_version_and_info() {
    local container_name="$1"
    local current_version current_revision created_date local_digest

    # Get version from container labels
    current_version=$(docker container inspect "$container_name" --format '{{index .Config.Labels "org.opencontainers.image.version"}}' 2>/dev/null || echo "")

    # Get git commit SHA from container labels
    current_revision=$(docker container inspect "$container_name" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' 2>/dev/null || echo "")

    # Get creation date for reference
    created_date=$(docker container inspect "$container_name" --format '{{index .Config.Labels "org.opencontainers.image.created"}}' 2>/dev/null || echo "")

    # Get RepoDigest from the container's image (most reliable for comparison)
    local image_id
    image_id=$(docker container inspect "$container_name" --format '{{.Image}}' 2>/dev/null || echo "")
    if [[ -n "$image_id" ]]; then
        local repo_digest
        repo_digest=$(docker image inspect "$image_id" --format '{{index .RepoDigests 0}}' 2>/dev/null || echo "")
        # Extract just the digest part (after @)
        local_digest="${repo_digest##*@}"
        local_digest="${local_digest#sha256:}"
    fi

    # Clean up results
    if [[ -z "$current_version" || "$current_version" == "<no value>" ]]; then
        current_version="unknown"
    fi

    if [[ -z "$current_revision" || "$current_revision" == "<no value>" ]]; then
        current_revision="unknown"
    fi

    if [[ -z "$created_date" || "$created_date" == "<no value>" ]]; then
        created_date=$(docker container inspect "$container_name" --format '{{.Created}}' 2>/dev/null || echo "")
        created_date=${created_date:0:19}
    fi

    if [[ -z "$local_digest" ]]; then
        local_digest="unknown"
    fi

    echo "$current_version|$current_revision|$created_date|$local_digest"
}

# Get latest version info from remote
get_latest_version_info() {
    local image_name="$1"

    log_info "Checking latest available version..."

    # Try to get version from the remote image metadata without jq dependency
    local latest_version
    latest_version=$(docker buildx imagetools inspect "$image_name" 2>/dev/null | \
                    grep -oE '"org.opencontainers.image.version":"[^"]*"' | \
                    sed 's/.*"org.opencontainers.image.version":"\([^"]*\)".*/\1/' || echo "latest")

    if [[ -n "$latest_version" && "$latest_version" != "latest" ]]; then
        echo "$latest_version"
    else
        echo "unknown"
        return 1
    fi
}

# Check if update is available using Git commit SHA comparison
check_for_update() {
    local image_name="$1"

    echo
    log_info "=== Version Check ==="

    # Get running container information
    log_info "Analyzing running container..."

    # Check if container is running
    if ! docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
        log_error "Container $CONTAINER_NAME is not running"
        log_info "Please start the container first with: docker compose up -d server"
        return 0  # Recommend update (to start container)
    fi

    local local_info local_version local_revision local_created local_digest
    local_info=$(identify_local_version_and_info "$CONTAINER_NAME")
    local_version="${local_info%%|*}"
    local_revision="${local_info#*|}"
    local_revision="${local_revision%%|*}"
    local_created="${local_info#*|*|}"
    local_created="${local_created%%|*}"
    local_digest="${local_info##*|}"

    log_info "Running container: $CONTAINER_NAME"
    log_info "Current version: $local_version"
    log_info "Local git commit: ${local_revision:0:12}..."
    log_info "Local RepoDigest: ${local_digest:0:12}..."
    if [[ -n "$local_created" && "$local_created" != "unknown" ]]; then
        log_info "Built: $local_created"
    fi

    # Get latest information from GitHub (inline to avoid subshell file cleanup issues)
    log_info "Fetching latest information from GitHub Container Registry..."
    local latest_version latest_revision versions_list latest_digest

    local temp_file="/tmp/goodmem_versions.html"
    local versions_url="https://github.com/PAIR-Systems-Inc/goodmem/pkgs/container/goodmem%2Fserver/versions"

    # Download the GitHub packages page
    if curl -s -L "$versions_url" -o "$temp_file" 2>/dev/null; then
        # Extract versions
        local versions
        versions=$(grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' "$temp_file" 2>/dev/null | \
                  sort -V -r | uniq | head -10)

        if [[ -n "$versions" ]]; then
            latest_version=$(echo "$versions" | head -1)
            versions_list=$(echo "$versions" | tr '\n' ' ')

            # Extract SHA for the latest version
            latest_revision=$(grep -A 5 -B 5 "$latest_version" "$temp_file" 2>/dev/null | \
                             grep -oE 'sha-[a-f0-9]{40}' | head -1 | sed 's/sha-//')

            # Extract digest for the latest version using proven method
            latest_digest=$(grep -A 20 "$latest_version" "$temp_file" 2>/dev/null | \
                           grep -oE 'sha256:[a-f0-9]{64}' | head -1 | sed 's/sha256://')

            # If digest extraction fails, try fallback methods
            if [[ -z "$latest_digest" ]]; then
                latest_digest=$(grep -B 20 "$latest_version" "$temp_file" 2>/dev/null | \
                               grep -oE 'sha256:[a-f0-9]{64}' | tail -1 | sed 's/sha256://')
            fi

            if [[ -z "$latest_digest" ]]; then
                latest_digest=$(grep -oE 'sha256:[a-f0-9]{64}' "$temp_file" | head -1 | sed 's/sha256://')
            fi

            # Debug output
            if [[ -n "$latest_digest" ]]; then
                log_info "Successfully extracted digest for $latest_version: ${latest_digest:0:12}..."
            else
                local digest_count
                digest_count=$(grep -c 'sha256:' "$temp_file" 2>/dev/null || echo "0")
                log_info "Digest extraction failed for $latest_version (found $digest_count total patterns)"
            fi
        else
            latest_version="unknown"
            latest_revision="unknown"
            latest_digest="unknown"
            versions_list=""
        fi

        # Show detailed version information before cleanup
        echo
        show_available_versions_with_details "$temp_file"
        echo

        rm -f "$temp_file"
    else
        log_warning "Could not fetch information from GitHub Container Registry"
        latest_version="unknown"
        latest_revision="unknown"
        latest_digest="unknown"
        versions_list=""

        # Show fallback message
        echo
        log_info "Recent versions available:"
        log_info "  (Could not fetch from GitHub - check manually at:)"
        log_info "  https://github.com/PAIR-Systems-Inc/goodmem/pkgs/container/goodmem%2Fserver/versions"
        echo
    fi

    if [[ "$latest_revision" != "unknown" ]]; then
        log_info "Latest git commit: ${latest_revision:0:12}..."
        log_info "Latest version tag: $latest_version"
    else
        log_warning "Could not fetch latest commit information from GitHub"
    fi

    if [[ "$latest_digest" != "unknown" ]]; then
        log_info "Latest RepoDigest: ${latest_digest:0:12}..."
    else
        log_warning "Could not fetch latest digest from GitHub"
    fi

    # Additional debug: show what we're comparing
    log_info "Comparison summary:"
    log_info "  Your container: $local_version (digest: ${local_digest:0:12}...)"
    log_info "  GitHub latest: $latest_version (digest: ${latest_digest:0:12}...)"

    # Detailed versions already shown above, skip duplicate display

    # Compare using RepoDigest (most reliable method for detecting image changes)
    if [[ "$local_digest" != "unknown" && "$latest_digest" != "unknown" ]]; then
        log_info "RepoDigest comparison:"
        log_info "  Local:  ${local_digest:0:16}..."
        log_info "  Remote: ${latest_digest:0:16}..."

        if [[ "$local_digest" == "$latest_digest" ]]; then
            log_success "✓ You have the latest version!"
            log_info "Local and remote RepoDigests match perfectly"
            log_info "Version: $local_version (digest: ${local_digest:0:12}...)"
            return 1  # No update needed
        else
            log_info "🔄 Update available!"
            log_info "Your version: $local_version (digest: ${local_digest:0:12}...)"
            log_info "Latest version: $latest_version (digest: ${latest_digest:0:12}...)"

            # Check if it's a version bump or code change
            if [[ "$local_revision" == "$latest_revision" && "$local_revision" != "unknown" ]]; then
                log_info "Same Git commit but different image - likely a version bump"
            else
                log_info "Different RepoDigest indicates image changes"
            fi

            return 0  # Update available
        fi
    else
        # Fallback when digest comparison isn't possible
        log_warning "Could not perform RepoDigest comparison"

        if [[ "$local_digest" == "unknown" ]]; then
            log_info "Local RepoDigest unavailable (image may lack registry metadata)"
        fi

        if [[ "$latest_digest" == "unknown" ]]; then
            log_info "Could not fetch latest digest from GitHub Container Registry"
        fi

        # Try Git commit comparison as fallback
        if [[ "$local_revision" != "unknown" && "$latest_revision" != "unknown" ]]; then
            if [[ "$local_revision" == "$latest_revision" ]]; then
                # Same commit - check version tags
                if [[ "$local_version" == "$latest_version" ]]; then
                    log_info "Git commits and versions match, likely up to date"
                    log_info "🔄 Update recommended to ensure latest image"
                else
                    log_info "🔄 Update available!"
                    log_info "Version upgrade: $local_version → $latest_version (same commit)"
                fi
            else
                log_info "🔄 Update available!"
                log_info "Git commit change: ${local_revision:0:12}... → ${latest_revision:0:12}..."
            fi
        else
            log_info "🔄 Update recommended to ensure you have the latest version"
        fi

        return 0  # Recommend update when uncertain
    fi
}

# Confirm action with user
confirm_action() {
    if [[ "$FORCE_MODE" == true ]]; then
        return 0
    fi

    local image_name="$1"
    echo
    echo -e "${YELLOW}This will:${NC}"
    echo "  1. Stop and remove the $CONTAINER_NAME container"
    echo "  2. Remove the Docker image: $image_name"
    echo "  3. Pull the latest version and restart the server"
    echo
    echo -e "${YELLOW}Warning: This will cause a brief service interruption.${NC}"
    echo

    read -p "Do you want to continue? [y/N]: " -r
    echo

    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Operation cancelled by user"
        exit 0
    fi
}

# Stop and remove container
stop_and_remove_container() {
    log_info "Stopping and removing container: $CONTAINER_NAME"

    # Check if container exists (running or stopped)
    if docker ps -a --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
        # Stop the container if running
        if docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
            log_info "Stopping running container..."
            if ! docker stop "$CONTAINER_NAME"; then
                log_error "Failed to stop container"
                exit 1
            fi
            log_success "Container stopped successfully"
        fi

        # Remove the container
        log_info "Removing container..."
        if ! docker rm "$CONTAINER_NAME"; then
            log_error "Failed to remove container"
            exit 1
        fi
        log_success "Container removed successfully"
    else
        log_warning "Container $CONTAINER_NAME not found, skipping removal"
    fi
}

# Remove Docker image
remove_image() {
    local image_name="$1"
    log_info "Removing Docker image: $image_name"

    # Check if image exists (without table format to avoid extra formatting)
    if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${image_name}$"; then
        if ! docker rmi "$image_name"; then
            log_error "Failed to remove image $image_name"
            exit 1
        fi
        log_success "Image removed successfully"
    else
        log_warning "Image $image_name not found locally, skipping removal"
        log_info "Available images matching 'goodmem':"
        docker images --format "  {{.Repository}}:{{.Tag}}" | grep goodmem || echo "  No goodmem images found"
    fi
}

# Start server with docker compose
start_server() {
    log_info "Starting server with docker compose..."

    # Change to goodmem directory for proper context
    cd "$GOODMEM_DIR"

    # Pull latest image and start server
    docker compose up -d "$SERVICE_NAME"

    log_success "Server started successfully"
}

# Wait for server to be ready
wait_for_server() {
    log_info "Waiting for server to be ready..."

    local max_attempts=30
    local attempt=1

    while [[ $attempt -le $max_attempts ]]; do
        # Check if container is running and healthy
        local container_status
        container_status=$(docker inspect "$CONTAINER_NAME" --format '{{.State.Status}}' 2>/dev/null || echo "not_found")

        if [[ "$container_status" == "running" ]]; then
            # Check health status if available
            local health_status
            health_status=$(docker inspect "$CONTAINER_NAME" --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}no_healthcheck{{end}}' 2>/dev/null || echo "unknown")

            if [[ "$health_status" == "healthy" || "$health_status" == "no_healthcheck" ]]; then
                log_success "Server is ready!"
                return 0
            elif [[ "$health_status" == "starting" ]]; then
                log_info "Attempt $attempt/$max_attempts - Server is starting, waiting 5 seconds..."
            else
                log_info "Attempt $attempt/$max_attempts - Server health: $health_status, waiting 5 seconds..."
            fi
        elif [[ "$container_status" == "not_found" ]]; then
            log_info "Attempt $attempt/$max_attempts - Container not found, waiting 5 seconds..."
        else
            log_info "Attempt $attempt/$max_attempts - Container status: $container_status, waiting 5 seconds..."
        fi

        sleep 5
        ((attempt++))
    done

    log_warning "Server health check timed out after $((max_attempts * 5)) seconds"
    log_info "You can check server status with: docker compose -f $DOCKER_COMPOSE_FILE ps"
}

# Show final status
show_status() {
    echo
    log_info "Final status:"
    cd "$GOODMEM_DIR"
    docker compose ps "$SERVICE_NAME"

    echo
    log_info "You can view server logs with:"
    echo "  docker compose -f $DOCKER_COMPOSE_FILE logs -f $SERVICE_NAME"
}

# Main execution
main() {
    parse_args "$@"

    if [[ "$CHECK_ONLY" == true ]]; then
        echo "=== GoodMem Server Version Check ==="
    else
        echo "=== GoodMem Server Reinstall Script ==="
    fi
    echo

    check_prerequisites

    local image_name
    image_name=$(get_image_name)
    log_info "Detected image: $image_name"

    # Check for updates
    if ! check_for_update "$image_name"; then
        log_success "Local image is already up to date!"
        if [[ "$CHECK_ONLY" == true ]]; then
            echo
            log_info "No update needed. Current version is the latest."
            exit 0
        fi

        if [[ "$FORCE_MODE" != true ]]; then
            echo
            echo -e "${YELLOW}Local image appears to be up to date.${NC}"
            read -p "Do you want to reinstall anyway? [y/N]: " -r
            echo

            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                log_info "Reinstall cancelled - image is up to date"
                exit 0
            fi
        fi
    else
        if [[ "$CHECK_ONLY" == true ]]; then
            echo
            log_info "Update available! Run without --check-only to update."
            exit 0
        fi
    fi

    # Confirm action if not in force mode and update is needed
    if [[ "$FORCE_MODE" != true ]]; then
        confirm_action "$image_name"
    fi

    stop_and_remove_container
    remove_image "$image_name"
    start_server
    wait_for_server
    show_status

    echo
    log_success "GoodMem server reinstall completed successfully!"
}

# Run main function if script is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi