#!/bin/bash
# Run the API key sample program using uv in a consistent, isolated environment
#
# IMPORTANT: This script is primarily for developers working on the client library.
# It uses the local source code in `goodmem_client/` directory rather than installing
# from PyPI. If you're a user of the library (not a developer), consider using
# run_apikey_sample_pypi.sh instead.
#
# The script:
# - Creates a virtual environment
# - Installs the local client library in editable mode
# - Runs the sample with the provided arguments
#
# Usage:
#   ./run_apikey_sample.sh [--verbose] <sample arguments>
#
# Options:
#   --verbose  Show setup progress messages (INFO: ...) during virtual environment 
#              creation and dependency installation.

set -e # Exit immediately if a command exits with a non-zero status.
set -u # Treat unset variables as an error when substituting.
set -o pipefail # The return value of a pipeline is the status of the last command to exit with a non-zero status.

# --- Configuration ---
# Get the directory of this script (which is assumed to be the project root: python/)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Name of the virtual environment directory to create/use for samples
# You can use a different venv name or the same as for tests if dependencies align
VENV_DIR_SAMPLE=".venv_sample_runner"
# Python interpreter to use for the virtual environment
PYTHON_INTERPRETER="python3"
# Path to the sample script relative to SCRIPT_DIR
SAMPLE_SCRIPT_PATH="samples/apikey_sample.py"

# Default to quiet mode (no INFO messages)
VERBOSE_MODE=0

# Parse our script arguments and filter out our flags for passing to Python
FILTERED_ARGS=()
for arg in "$@"; do
    if [[ "$arg" == "--verbose" ]]; then
        VERBOSE_MODE=1
    else
        FILTERED_ARGS+=("$arg")
    fi
done

# --- Script Start ---
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Starting API key sample execution script..."
fi

# Check for trailing slash in server URL (if provided as an argument)
if [ $VERBOSE_MODE -eq 1 ]; then
    for arg in "$@"; do
        if [[ "$arg" == "--server="* && "$arg" == */ ]]; then
            echo "NOTE: Server URL has a trailing slash. The script will automatically trim it to prevent URL path issues."
        fi
    done
fi

# Ensure the script is run from the project root (where pyproject.toml is)
# This is important for `uv pip install -e .`
cd "$SCRIPT_DIR"

# Check if uv is installed
if ! command -v uv &> /dev/null; then
    echo "ERROR: uv command not found. Please install uv first."
    echo "       You can typically install it using: pip install uv"
    exit 1
fi

# 1. Create/update the virtual environment
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Setting up virtual environment in '$VENV_DIR_SAMPLE' using '$PYTHON_INTERPRETER'..."
fi

# Create/update virtual environment using uv's quiet mode by default
if uv venv "$VENV_DIR_SAMPLE" --python "$PYTHON_INTERPRETER" -q; then
    if [ $VERBOSE_MODE -eq 1 ]; then
        echo "INFO: Virtual environment created/updated successfully."
    fi
else
    echo "ERROR: Failed to create/update virtual environment. Ensure '$PYTHON_INTERPRETER' is a valid Python interpreter."
    exit 1
fi

# Determine the Python executable path within the venv
PYTHON_IN_VENV_SAMPLE="$VENV_DIR_SAMPLE/bin/python"
if [ ! -f "$PYTHON_IN_VENV_SAMPLE" ]; then
    # Fallback for Windows-style venv path if bin/python doesn't exist (though this script is bash)
    if [ -f "$VENV_DIR_SAMPLE/Scripts/python.exe" ]; then
        PYTHON_IN_VENV_SAMPLE="$VENV_DIR_SAMPLE/Scripts/python.exe"
    else
        echo "ERROR: Python executable not found in virtual environment path: $VENV_DIR_SAMPLE/bin/python or $VENV_DIR_SAMPLE/Scripts/python.exe"
        exit 1
    fi
fi

# 2. Install the project (goodmem_client) and its runtime dependencies into the venv
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Installing project and its runtime dependencies into '$VENV_DIR_SAMPLE'..."
fi

# Using -e . installs the current directory project in editable mode.
# This ensures 'goodmem_client' is importable by the sample script.
if uv pip install -e . --python "$PYTHON_IN_VENV_SAMPLE" -q; then
    if [ $VERBOSE_MODE -eq 1 ]; then
        echo "INFO: Project and its dependencies installed successfully."
    fi
else
    echo "ERROR: Failed to install project and its dependencies."
    exit 1
fi

# 3. Run the sample script using the Python interpreter from the virtual environment
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Running sample script: $SAMPLE_SCRIPT_PATH ..."
fi

# Run the sample script
if "$PYTHON_IN_VENV_SAMPLE" "$SAMPLE_SCRIPT_PATH" "${FILTERED_ARGS[@]}"; then
    if [ $VERBOSE_MODE -eq 1 ]; then
        echo "INFO: Sample script execution completed successfully."
    fi
else
    echo "ERROR: Sample script execution failed."
    exit 1
fi

if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: API key sample script finished."
fi
