#!/bin/bin/env bash
set -euo pipefail

ENV="${1:-staging}"
VERSION="${2:-latest}"
DEPLOY_TIME=$(date +"%Y-%m-%d %H:%M:%S")

echo "========================================="
echo "  Deployment Script"
echo "========================================="
echo "Environment: $ENV"
echo "Version:     $VERSION"
echo "Timestamp:   $DEPLOY_TIME"
echo "========================================="

check_dependencies() {
    local deps=("docker" "kubectl" "helm")
    for dep in "${deps[@]}"; do
        if ! command -v "$dep" &>/dev/null; then
            echo "ERROR: $dep is not installed"
            exit 1
        fi
    done
    echo "All dependencies satisfied."
}

run_health_check() {
    local max_retries=5
    local retry=0
    while [ $retry -lt $max_retries ]; do
        if curl -sf http://localhost:8080/health > /dev/null 2>&1; then
            echo "Health check passed."
            return 0
        fi
        retry=$((retry + 1))
        echo "Health check failed, retry $retry/$max_retries..."
        sleep 3
    done
    echo "ERROR: Health check failed after $max_retries retries."
    return 1
}

check_dependencies
echo "Deploying version $VERSION to $ENV..."
run_health_check
echo "Deployment complete."
