#!/usr/bin/env zsh

# Function to display usage information
usage() {
    echo "Usage: source $0 <environment> [version]"
    echo "  environment: The environment to use (dev, prod, test, integration, bugfix)"
    echo "  version    : (Optional) Specific release version to deploy"
    echo "               If not specified, uses 'latest' (except for dev environment)"
}

# 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> [version]"
    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
VERSION=${2:-latest}  # Default to latest if not specified

# Check if podman and podman-compose are available
if ! command -v podman &> /dev/null; then
    echo "Error: podman is not installed or not in PATH"
    echo "Please install podman first"
    return 1
fi

if ! command -v podman-compose &> /dev/null; then
    echo "Error: podman-compose is not installed or not in PATH"
    echo "Please install podman-compose first"
    return 1
fi

CONTAINER_CMD="podman"
# Store the actual path to podman-compose to avoid recursion
COMPOSE_CMD_PATH=$(command -v podman-compose)

echo "Using container runtime: $CONTAINER_CMD"
echo "Using compose command: $COMPOSE_CMD_PATH"

# Set default platform to AMD64 for consistency
export BUILDAH_PLATFORM=linux/amd64
export PODMAN_PLATFORM=linux/amd64

# Set variables based on the environment
case $ENVIRONMENT in
    dev)
        PODMAN_CONNECTION="default"
        COMPOSE_FILE="compose_dev.yaml"
        REGISTRY_PREFIX=""
        COMPOSE_PROJECT_NAME="eveai_dev"
        VERSION="latest"  # Always use latest for dev
        ;;
    prod)
        # TO BE DEFINED
        PODMAN_CONNECTION="mxz536.stackhero-network.com"
        COMPOSE_FILE="compose_stackhero.yaml"
        REGISTRY_PREFIX=""
        COMPOSE_PROJECT_NAME="eveai_prod"
        ;;
    test)
        PODMAN_CONNECTION="test-environment"
        COMPOSE_FILE="compose_test.yaml"
        REGISTRY_PREFIX="registry.ask-eve-ai-local.com/"
        COMPOSE_PROJECT_NAME="eveai_test"
        ;;
    bugfix)
        # TO BE DEFINED
        PODMAN_CONNECTION="bugfix-environment"
        COMPOSE_FILE="compose_bugfix.yaml"
        COMPOSE_PROJECT_NAME="eveai_bugfix"
        ;;
    *)
        echo "Invalid environment: $ENVIRONMENT"
        usage
        return 1
        ;;
esac

# Set container registry account
CONTAINER_ACCOUNT="josakola"

# Handle remote connections for podman
if [[ "$PODMAN_CONNECTION" != "default" ]]; then
    echo "Setting up remote podman connection: $PODMAN_CONNECTION"

    # Check if podman connection exists
    if ! podman system connection list --format '{{.Name}}' 2>/dev/null | grep -q "^$PODMAN_CONNECTION$"; then
        echo "Warning: Podman connection '$PODMAN_CONNECTION' does not exist."
        echo -n "Do you want to set up this connection now? (y/n): "
        read -r CREATE_CONNECTION
        if [[ "$CREATE_CONNECTION" == "y" || "$CREATE_CONNECTION" == "Y" ]]; then
            echo -n "Please specify the SSH connection string (e.g., user@remote_host): "
            read -r SSH_CONNECTION

            if [[ -n "$SSH_CONNECTION" ]]; then
                podman system connection add "$PODMAN_CONNECTION" --identity ~/.ssh/id_rsa "ssh://$SSH_CONNECTION/run/user/1000/podman/podman.sock"
                if [[ $? -ne 0 ]]; then
                    echo "Failed to create podman connection. Please create it manually."
                    return 1
                fi
            else
                echo "No SSH connection string provided."
                return 1
            fi
        else
            echo "Using local podman setup instead."
            PODMAN_CONNECTION="default"
        fi
    fi

    # Set the connection
    if [[ "$PODMAN_CONNECTION" != "default" ]]; then
        # Use podman context instead of manually setting CONTAINER_HOST
        podman system connection default "$PODMAN_CONNECTION" 2>/dev/null
        if [[ $? -eq 0 ]]; then
            echo "Switched to remote podman connection: $PODMAN_CONNECTION"
        else
            echo "Warning: Failed to switch to connection $PODMAN_CONNECTION, using local setup"
            PODMAN_CONNECTION="default"
        fi
    fi
else
    echo "Using local podman setup with AMD64 platform"
    # Ensure we're using the default local connection
    podman system connection default "" 2>/dev/null || true
fi

# Check if compose file exists
if [[ ! -f "$COMPOSE_FILE" ]]; then
    echo "Warning: Compose file '$COMPOSE_FILE' does not exist."
    if [[ -f "compose_dev.yaml" ]]; then
        echo -n "Do you want to create it based on compose_dev.yaml? (y/n): "
        read -r CREATE_FILE
        if [[ "$CREATE_FILE" == "y" || "$CREATE_FILE" == "Y" ]]; then
            # Create new compose file based on compose_dev.yaml with version variables
            if sed 's/\(image: josakola\/[^:]*\):latest/\1:${EVEAI_VERSION:-latest}/g' compose_dev.yaml > "$COMPOSE_FILE" 2>/dev/null; then
                echo "Created $COMPOSE_FILE with version placeholders."
            else
                echo "Failed to create $COMPOSE_FILE"
                return 1
            fi
        else
            echo "Cannot proceed without a valid compose file."
            return 1
        fi
    else
        echo "Cannot create $COMPOSE_FILE: compose_dev.yaml not found."
        return 1
    fi
fi

# Set environment variables
export COMPOSE_FILE=$COMPOSE_FILE
export EVEAI_VERSION=$VERSION
export CONTAINER_ACCOUNT=$CONTAINER_ACCOUNT
export CONTAINER_CMD=$CONTAINER_CMD
export COMPOSE_CMD_PATH=$COMPOSE_CMD_PATH
export REGISTRY_PREFIX=$REGISTRY_PREFIX
export COMPOSE_PROJECT_NAME=$COMPOSE_PROJECT_NAME

echo "Set COMPOSE_FILE to $COMPOSE_FILE"
echo "Set EVEAI_VERSION to $VERSION"
echo "Set CONTAINER_ACCOUNT to $CONTAINER_ACCOUNT"
echo "Set platform to AMD64 (linux/amd64)"
echo "Set registry prefix to $REGISTRY_PREFIX"
echo "Set project name to $COMPOSE_PROJECT_NAME"

# Define compose wrapper functions using the full path to avoid recursion
pc() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE "$@"
}

pcup() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE up -d --remove-orphans "$@"
}

pcdown() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE down "$@"
}

pcps() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE ps "$@"
}

pclogs() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE logs "$@"
}

pcpull() {
    echo "Pulling AMD64 images..."
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE pull "$@"
}

pcrefresh() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE pull && $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE up -d --remove-orphans "$@"
}

pcbuild() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE build "$@"
}

pcrestart() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE restart "$@"
}

pcstop() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE stop "$@"
}

pcstart() {
    $COMPOSE_CMD_PATH -p ${COMPOSE_PROJECT_NAME} -f $COMPOSE_FILE start "$@"
}
# 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 pc pcup pcdown pcps pclogs pcpull pcrefresh pcbuild pcrestart pcstop pcstart > /dev/null
else
    # Bash style export
    export -f pc pcup pcdown pcps pclogs pcpull pcrefresh pcbuild pcrestart pcstop pcstart
fi

echo "✅ Podman environment switched to $ENVIRONMENT with version $VERSION"
echo "🖥️  Platform: AMD64 (compatible with both Intel and Apple Silicon)"
echo "Available commands:"
echo "  pc        - podman-compose shorthand"
echo "  pcup      - start services in background"
echo "  pcdown    - stop and remove services"
echo "  pcps      - list running services"
echo "  pclogs    - view service logs"
echo "  pcpull    - pull latest images"
echo "  pcrefresh - pull and restart services"
echo "  pcbuild   - build services"
echo "  pcrestart - restart services"
echo "  pcstop    - stop services"
echo "  pcstart   - start stopped services"