#!/usr/bin/env bash
# Launcher: set up the environment and run the phynx CLI from this checkout.
# Works from any working directory, with or without an installed package.
set -euo pipefail

script_path="$(readlink -f "${BASH_SOURCE[0]}")"
repository_root="$(dirname "$(dirname "$script_path")")"

# Make the in-tree package importable without an install step.
export PYTHONPATH="$repository_root/src${PYTHONPATH:+:$PYTHONPATH}"

# Pin the nix C API library directory for the embedded evaluator, unless
# the caller already chose one.  Derived from the active nix executable.
if [ -z "${PHYNX_NIX_LIB_DIR:-}" ] && command -v nix > /dev/null; then
    nix_executable="$(readlink -f "$(command -v nix)")"
    nix_library_dir="$(dirname "$(dirname "$nix_executable")")/lib"
    if [ -e "$nix_library_dir/libnixexprc.so" ]; then
        export PHYNX_NIX_LIB_DIR="$nix_library_dir"
    fi
fi

# Prefer the project virtualenv; fall back to any python3 (stdlib is enough).
if [ -x "$repository_root/.venv/bin/python" ]; then
    python_executable="$repository_root/.venv/bin/python"
else
    python_executable="python3"
fi

exec "$python_executable" -m phynx.cli "$@"
