#!/usr/bin/env bash
# Open an interactive envelope plot in your browser (matplotlib WebAgg).
#
# On NixOS, the prebuilt numpy wheel needs libstdc++ from gcc-lib on
# LD_LIBRARY_PATH; this wrapper finds it automatically.
#
# Usage:
#   tools/show_envelope.sh <episode_dir> [--port 8988]
#
# Then open the printed URL (or your browser may pop open automatically).
# Ctrl-C in this terminal to stop the server.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

# Locate libstdc++.so.6 in /nix/store. Prefer the gcc-lib derivation.
LIBSTDC=$(find /nix/store -maxdepth 4 -name 'libstdc++.so.6' -path '*gcc*-lib/lib/*' 2>/dev/null | head -1)
if [[ -z "${LIBSTDC:-}" ]]; then
    # Fall back to any libstdc++ in /nix/store.
    LIBSTDC=$(find /nix/store -maxdepth 4 -name 'libstdc++.so.6' 2>/dev/null | head -1)
fi
if [[ -z "${LIBSTDC:-}" ]]; then
    echo "could not locate libstdc++.so.6 in /nix/store" >&2
    echo "(numpy needs it; install via 'nix-shell -p stdenv.cc.cc.lib' or set LD_LIBRARY_PATH manually)" >&2
    exit 1
fi
LIB_DIR="$(dirname "$LIBSTDC")"

LD_LIBRARY_PATH="$LIB_DIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    exec uv run python tools/plot_envelope.py --show "$@"
