#!/bin/bash

# PyMoo tool execution wrapper with conda environment support
# This script can execute tools from the tools directory or run Python directly

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYMOO_ROOT="$(dirname "$SCRIPT_DIR")"

# Change to pymoo root directory to ensure consistent behavior
cd "$PYMOO_ROOT"

# Load environment variables from .env
if [ -f "$SCRIPT_DIR/.env" ]; then
    export $(grep -v '^#' "$SCRIPT_DIR/.env" | xargs)
fi

# Use default environment if not specified
CONDA_ENV="${CONDA_ENV:-default}"

# Add pymoo to Python path
export PYTHONPATH="$PYMOO_ROOT:$PYTHONPATH"

# Activate conda environment
source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "$CONDA_ENV"

# Check if first argument is a tool in the tools directory
if [ $# -gt 0 ] && [ -f "$SCRIPT_DIR/$1" ]; then
    # First argument is a tool script, execute it with remaining arguments
    TOOL_SCRIPT="$SCRIPT_DIR/$1"
    shift  # Remove the tool name from arguments
    python "$TOOL_SCRIPT" "$@"
    exit_code=$?
else
    # Execute Python with all passed arguments (original behavior)
    python "$@"
    exit_code=$?
fi

# Exit with the same code as the executed command
exit $exit_code