#!/usr/bin/env zsh

# Function to display usage information
usage() {
    echo "Usage: source $0 <environment>"
    echo "  environment: The Scaleway environment to use (staging|production)"
    echo ""
    echo "Examples:"
    echo "  source $0 staging"
    echo "  source $0 production"
}

# Check if the script is sourced - improved for both bash and zsh
is_sourced() {
    if [[ -n "$ZSH_VERSION" ]]; then
        # In zsh, check if we're in a sourced context
        [[ "$ZSH_EVAL_CONTEXT" =~ "(:file|:cmdsubst)" ]] || [[ "$0" != "$ZSH_ARGZERO" ]]
    else
        # In bash, compare BASH_SOURCE with $0
        [[ "${BASH_SOURCE[0]}" != "${0}" ]]
    fi
}

if ! is_sourced; then
    echo "❌ Error: This script must be sourced, not executed directly."
    echo "Please run: source $0 <environment>"
    if [[ -n "$ZSH_VERSION" ]]; then
        return 1 2>/dev/null || exit 1
    else
        exit 1
    fi
fi

# Check if an environment is provided
if [ $# -eq 0 ]; then
    usage
    return 1
fi

ENVIRONMENT=$1

# Validate environment
if [[ "$ENVIRONMENT" != "staging" && "$ENVIRONMENT" != "production" ]]; then
    echo "❌ Invalid environment: $ENVIRONMENT"
    usage
    return 1
fi

# Get script directory to find config files
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/configs/$ENVIRONMENT.conf"

# Check if config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "❌ Error: Config file not found: $CONFIG_FILE"
    echo "   Please create the config file with Scaleway credentials"
    return 1
fi

# Load configuration
echo "📋 Loading Scaleway $ENVIRONMENT configuration..."
source "$CONFIG_FILE"

# Validate required config variables
if [[ -z "$SCALEWAY_REGISTRY" || -z "$SCALEWAY_API_KEY" ]]; then
    echo "❌ Error: Missing required configuration in $CONFIG_FILE"
    echo "   Required: SCALEWAY_REGISTRY, SCALEWAY_API_KEY"
    return 1
fi

# Check if kubectl is available for K8s context switching
KUBECTL_AVAILABLE=false
if command -v kubectl &> /dev/null; then
    KUBECTL_AVAILABLE=true
else
    echo "⚠️  Warning: kubectl not found - K8s context switching will be skipped"
fi

echo "☁️  Scaleway Environment Switch"
echo "🌍 Environment: $ENVIRONMENT"
echo "🏪 Registry: $SCALEWAY_REGISTRY"
echo "🌐 Region: ${SCALEWAY_REGION:-fr-par}"

# Set environment variables
export SCALEWAY_ENVIRONMENT=$ENVIRONMENT
export SCALEWAY_REGISTRY=$SCALEWAY_REGISTRY
export SCALEWAY_API_KEY=$SCALEWAY_API_KEY
export SCALEWAY_REGION=${SCALEWAY_REGION:-fr-par}
export SCALEWAY_PROJECT_ID=${SCALEWAY_PROJECT_ID:-}

# Handle kubectl context switching if available
if [[ "$KUBECTL_AVAILABLE" == true && -n "$K8S_CONTEXT" ]]; then
    echo "🔄 Switching kubectl context..."
    
    # Check if the context exists
    if kubectl config get-contexts "$K8S_CONTEXT" &>/dev/null; then
        if kubectl config use-context "$K8S_CONTEXT" &>/dev/null; then
            echo "✅ Switched to kubectl context: $K8S_CONTEXT"
            export KUBECTL_CONTEXT=$K8S_CONTEXT
        else
            echo "⚠️  Warning: Failed to switch to kubectl context: $K8S_CONTEXT"
        fi
    else
        echo "⚠️  Warning: kubectl context '$K8S_CONTEXT' does not exist"
        echo "   💡 You may need to configure this context manually"
    fi
elif [[ -n "$K8S_CONTEXT" ]]; then
    echo "⚠️  kubectl not available - context switching skipped"
    export KUBECTL_CONTEXT=$K8S_CONTEXT
fi

# Define helper functions for Scaleway operations
scaleway_login() {
    echo "🔐 Logging into Scaleway registry..."
    
    # Extract registry hostname from full registry URL
    REGISTRY_HOST=$(echo "$SCALEWAY_REGISTRY" | cut -d'/' -f1)
    
    # Login to Scaleway registry using API key
    if echo "$SCALEWAY_API_KEY" | podman login --username nologin --password-stdin "$REGISTRY_HOST"; then
        echo "✅ Successfully logged into Scaleway registry"
    else
        echo "❌ Failed to login to Scaleway registry"
        return 1
    fi
}

scaleway_logout() {
    echo "🔓 Logging out of Scaleway registry..."
    
    # Extract registry hostname from full registry URL
    REGISTRY_HOST=$(echo "$SCALEWAY_REGISTRY" | cut -d'/' -f1)
    
    if podman logout "$REGISTRY_HOST" 2>/dev/null; then
        echo "✅ Successfully logged out of Scaleway registry"
    else
        echo "⚠️  Warning: Could not logout of Scaleway registry (may not have been logged in)"
    fi
}

scaleway_info() {
    echo "📋 Current Scaleway Configuration:"
    echo "   🌍 Environment: $SCALEWAY_ENVIRONMENT"
    echo "   🏪 Registry: $SCALEWAY_REGISTRY"
    echo "   🌐 Region: $SCALEWAY_REGION"
    if [[ -n "$SCALEWAY_PROJECT_ID" ]]; then
        echo "   📁 Project ID: $SCALEWAY_PROJECT_ID"
    fi
    if [[ -n "$KUBECTL_CONTEXT" ]]; then
        echo "   ⚙️  K8s Context: $KUBECTL_CONTEXT"
    fi
    if [[ -n "$K8S_CLUSTER_NAME" ]]; then
        echo "   🏗️  Cluster: $K8S_CLUSTER_NAME"
    fi
}

scaleway_push() {
    local version="$1"
    if [[ -z "$version" ]]; then
        echo "❌ Error: Version is required"
        echo "Usage: scaleway_push <version> [services]"
        return 1
    fi
    
    shift
    local services="$*"
    
    echo "🚀 Pushing version $version to Scaleway $SCALEWAY_ENVIRONMENT..."
    
    if [[ -n "$services" ]]; then
        "$SCRIPT_DIR/push_to_scaleway.sh" "$version" "$SCALEWAY_ENVIRONMENT" --services "$services"
    else
        "$SCRIPT_DIR/push_to_scaleway.sh" "$version" "$SCALEWAY_ENVIRONMENT"
    fi
}

# Export functions - handle both bash and zsh
if [[ -n "$ZSH_VERSION" ]]; then
    # In zsh, functions are automatically available in subshells
    # But we can make them available globally with typeset
    typeset -f scaleway_login scaleway_logout scaleway_info scaleway_push > /dev/null
else
    # Bash style export
    export -f scaleway_login scaleway_logout scaleway_info scaleway_push
fi

echo ""
echo "✅ Scaleway environment switched to $ENVIRONMENT"
echo "☁️  Registry: $SCALEWAY_REGISTRY"
if [[ -n "$KUBECTL_CONTEXT" ]]; then
    echo "⚙️  kubectl context: $KUBECTL_CONTEXT"
fi
echo ""
echo "Available commands:"
echo "  scaleway_login  - Login to Scaleway registry"
echo "  scaleway_logout - Logout from Scaleway registry"
echo "  scaleway_info   - Show current configuration"
echo "  scaleway_push   - Push version to current environment"
echo ""
echo "💡 Example usage:"
echo "  scaleway_login"
echo "  scaleway_push v1.2.3-alpha"
echo "  scaleway_push v2.0.0 eveai_api,eveai_workers"