#!/bin/bash
# Run the streaming sample program using the published goodmem-client PyPI package
#
# IMPORTANT: This script demonstrates how to use the client as a regular user would,
# by installing the published package from PyPI rather than using local source code.
# This is the recommended approach for users who are not developing the client library.
#
# The script:
# - Creates a virtual environment
# - Installs the goodmem-client package from PyPI
# - Copies the sample scripts to the virtual environment
# - Runs the sample with the provided arguments
#
# Usage:
#   ./run_streaming_sample_pypi.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_pypi"
# Python interpreter to use for the virtual environment
PYTHON_INTERPRETER="python3"
# Path to the sample script relative to SCRIPT_DIR
SAMPLE_SCRIPT_PATH="samples/streaming_sample.py"
# Package name to install from PyPI
PACKAGE_NAME="goodmem-client"

# 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 streaming sample execution script (PyPI version)..."
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)
cd "$SCRIPT_DIR"

# Check if required tools are installed
if ! command -v uv &> /dev/null && ! command -v pip &> /dev/null; then
    echo "ERROR: Neither uv nor pip is available. At least one is required."
    exit 1
fi

# Create a virtual environment for the sample if it doesn't exist
if [ ! -d "$VENV_DIR_SAMPLE" ]; then
    if [ $VERBOSE_MODE -eq 1 ]; then
        echo "INFO: Creating virtual environment in '$VENV_DIR_SAMPLE'..."
    fi
    
    if command -v uv &> /dev/null; then
        # Use uv with 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 successfully."
            fi
        else
            echo "ERROR: Failed to create virtual environment with uv."
            exit 1
        fi
    else
        # Fall back to standard venv
        if $PYTHON_INTERPRETER -m venv "$VENV_DIR_SAMPLE"; then
            if [ $VERBOSE_MODE -eq 1 ]; then
                echo "INFO: Virtual environment created successfully."
            fi
        else
            echo "ERROR: Failed to create virtual environment with standard venv."
            exit 1
        fi
    fi
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

# Install the goodmem-client package from PyPI
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Installing $PACKAGE_NAME package from PyPI..."
fi

if command -v uv &> /dev/null; then
    # Use uv with quiet mode by default, always upgrade to latest version
    if uv pip install --python "$PYTHON_IN_VENV_SAMPLE" "$PACKAGE_NAME" --upgrade -q; then
        if [ $VERBOSE_MODE -eq 1 ]; then
            echo "INFO: Package installed successfully."
        fi
    else
        echo "ERROR: Failed to install $PACKAGE_NAME package with uv."
        exit 1
    fi
else
    # Fall back to standard pip with quiet mode by default, always upgrade to latest version
    if "$PYTHON_IN_VENV_SAMPLE" -m pip install "$PACKAGE_NAME" --upgrade --quiet; then
        if [ $VERBOSE_MODE -eq 1 ]; then
            echo "INFO: Package installed successfully."
        fi
    else
        echo "ERROR: Failed to install $PACKAGE_NAME package with pip."
        exit 1
    fi
fi

# Copy the sample script to the venv
SAMPLES_DIR="$VENV_DIR_SAMPLE/samples"
mkdir -p "$SAMPLES_DIR"
cp "$SAMPLE_SCRIPT_PATH" "$SAMPLES_DIR/"
cp "$(dirname "$SAMPLE_SCRIPT_PATH")"/common.py "$SAMPLES_DIR/"

# Run the sample script using the venv Python
if [ $VERBOSE_MODE -eq 1 ]; then
    echo "INFO: Running sample script..."
fi

# Run the sample script
if "$PYTHON_IN_VENV_SAMPLE" "$SAMPLES_DIR/$(basename "$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: Streaming sample script finished."
fi