#!/bin/bash

# Deployment script for infra-mvp Helm chart
# Supports both Docker and Podman (defaults to Docker)

set -e

# Change to script directory
cd "$(dirname "$0")"

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

# Configuration
CHART_NAME="infra-mvp"
NAMESPACE="yera"
RELEASE_NAME="infra-mvp"
IMAGE_NAME="yera-infra-mvp"
IMAGE_TAG="latest"
CONTAINER_RUNTIME="docker" # Default to docker

# Print colored message
print_msg() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Check if running in minikube or kind
detect_k8s_environment() {
    if kubectl config current-context | grep -q "minikube"; then
        echo "minikube"
    elif kubectl config current-context | grep -q "kind"; then
        echo "kind"
    else
        echo "other"
    fi
}

# Build container image
build_image() {
    print_msg "$YELLOW" "Building image with $CONTAINER_RUNTIME..."
    
    if [ "$CONTAINER_RUNTIME" = "podman" ]; then
        # Podman: build with docker format for better compatibility
        $CONTAINER_RUNTIME build --format docker -t ${IMAGE_NAME}:${IMAGE_TAG} ../../
    else
        # Docker: normal build
        $CONTAINER_RUNTIME build -t ${IMAGE_NAME}:${IMAGE_TAG} ../../
    fi
    
    if [ $? -eq 0 ]; then
        print_msg "$GREEN" "✓ Image built successfully with $CONTAINER_RUNTIME"
    else
        print_msg "$RED" "✗ Failed to build image"
        exit 1
    fi
}

# Load image into cluster (for minikube/kind)
load_image() {
    local env=$(detect_k8s_environment)
    
    if [ "$env" = "minikube" ]; then
        print_msg "$YELLOW" "Loading image into minikube..."
        if [ "$CONTAINER_RUNTIME" = "podman" ]; then
            # Podman: save in docker format and load into minikube
            print_msg "$YELLOW" "Exporting image from podman in docker format..."
            $CONTAINER_RUNTIME save ${IMAGE_NAME}:${IMAGE_TAG} --format docker-archive -o /tmp/${IMAGE_NAME}.tar
            minikube image load /tmp/${IMAGE_NAME}.tar
            rm /tmp/${IMAGE_NAME}.tar
        else
            # Docker: direct load
            minikube image load ${IMAGE_NAME}:${IMAGE_TAG}
        fi
        print_msg "$GREEN" "✓ Image loaded into minikube"
    elif [ "$env" = "kind" ]; then
        print_msg "$YELLOW" "Loading image into kind..."
        if [ "$CONTAINER_RUNTIME" = "podman" ]; then
            # Podman: save in docker format and load
            print_msg "$YELLOW" "Exporting image from podman in docker format..."
            $CONTAINER_RUNTIME save ${IMAGE_NAME}:${IMAGE_TAG} --format docker-archive -o /tmp/${IMAGE_NAME}.tar
            kind load image-archive /tmp/${IMAGE_NAME}.tar
            rm /tmp/${IMAGE_NAME}.tar
        else
            # Docker: direct load
            kind load docker-image ${IMAGE_NAME}:${IMAGE_TAG}
        fi
        print_msg "$GREEN" "✓ Image loaded into kind"
    else
        print_msg "$YELLOW" "Skipping image load (not minikube or kind)"
    fi
}

# Create namespace if it doesn't exist
create_namespace() {
    if kubectl get namespace $NAMESPACE > /dev/null 2>&1; then
        print_msg "$YELLOW" "Namespace '$NAMESPACE' already exists"
    else
        print_msg "$YELLOW" "Creating namespace '$NAMESPACE'..."
        kubectl create namespace $NAMESPACE
        print_msg "$GREEN" "✓ Namespace created"
    fi
}

# Deploy or upgrade Helm chart
deploy_chart() {
    print_msg "$YELLOW" "Deploying Helm chart..."
    
    if helm list -n $NAMESPACE | grep -q $RELEASE_NAME; then
        print_msg "$YELLOW" "Upgrading existing release..."
        helm upgrade $RELEASE_NAME . --namespace $NAMESPACE "$@"
    else
        print_msg "$YELLOW" "Installing new release..."
        helm install $RELEASE_NAME . --namespace $NAMESPACE "$@"
    fi
    
    if [ $? -eq 0 ]; then
        print_msg "$GREEN" "✓ Helm chart deployed successfully"
    else
        print_msg "$RED" "✗ Failed to deploy Helm chart"
        exit 1
    fi
}

# Wait for deployments to be ready
wait_for_deployments() {
    print_msg "$YELLOW" "Waiting for deployments to be ready..."
    
    local deployments=$(kubectl get deployments -n $NAMESPACE -o name | grep $RELEASE_NAME)
    
    for deployment in $deployments; do
        kubectl rollout status $deployment -n $NAMESPACE --timeout=300s
    done
    
    print_msg "$GREEN" "✓ All deployments are ready"
}

# Show deployment status
show_status() {
    print_msg "$GREEN" "\n=== Deployment Status ==="
    kubectl get all -n $NAMESPACE
    
    print_msg "$GREEN" "\n=== Pods ==="
    kubectl get pods -n $NAMESPACE -o wide
    
    print_msg "$GREEN" "\n=== Services ==="
    kubectl get svc -n $NAMESPACE
    
    print_msg "$GREEN" "\n=== Port Forward Commands ==="
    echo "API Server:    kubectl port-forward -n $NAMESPACE svc/${RELEASE_NAME}-api 8989:8989"
    echo "IAM Server:    kubectl port-forward -n $NAMESPACE svc/${RELEASE_NAME}-iam 8990:8990"
    echo "Stream Server: kubectl port-forward -n $NAMESPACE svc/${RELEASE_NAME}-stream 8991:8991"
}

# Main deployment flow
main() {
    print_msg "$GREEN" "=== Yera Infrastructure MVP Deployment ==="
    
    # Parse runtime (optional, defaults to docker)
    local remaining_args=()
    if [ $# -gt 0 ] && [[ "$1" == "docker" || "$1" == "podman" ]]; then
        CONTAINER_RUNTIME=$1
        shift
    fi
    
    # Verify runtime
    print_msg "$GREEN" "Using container runtime: $CONTAINER_RUNTIME"
    if ! command -v $CONTAINER_RUNTIME &> /dev/null; then
        print_msg "$RED" "Error: $CONTAINER_RUNTIME is not installed or not in PATH"
        exit 1
    fi
    
    # Parse remaining command line arguments
    local skip_build=true
    local skip_load=true
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-build)
                skip_build=true
                shift
                ;;
            --skip-load)
                skip_load=true
                shift
                ;;
            *)
                break
                ;;
        esac
    done
    
    # Build image unless skipped
    if [ "$skip_build" = false ]; then
        build_image
    else
        print_msg "$YELLOW" "Skipping image build"
    fi
    
    # Load image unless skipped
    if [ "$skip_load" = false ]; then
        load_image
    else
        print_msg "$YELLOW" "Skipping image load"
    fi
    
    # Create namespace
    create_namespace
    
    # Deploy chart with any additional arguments
    deploy_chart "$@"
    
    # Wait for deployments
    wait_for_deployments
    
    # Show status
    show_status
    
    print_msg "$GREEN" "\n✓ Deployment complete!"
}

# Run main function with all arguments
main "$@"