#!/bin/bash
# IsoMap Python sidecar wrapper (Linux)
# Tauri sidecar: receives JSON-RPC request as first argument,
# runs the Python backend, returns JSON-RPC response on stdout.
set -euo pipefail

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

export PYTHONPATH="${REPO_ROOT}/src:${PYTHONPATH:-}"

# Discover Python 3.12+ (prefer python3, fall back to python).
# Use Python itself to do the version check — bash string comparison
# is unreliable for tuple-shaped version strings like "(3, 12)".
PYTHON=""
for candidate in python3 python; do
    if command -v "$candidate" >/dev/null 2>&1; then
        # Ask Python whether it's 3.12+; exit code 0 means yes.
        if "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' 2>/dev/null; then
            PYTHON="$candidate"
            break
        fi
    fi
done

if [[ -z "$PYTHON" ]]; then
    echo '{"jsonrpc":"2.0","error":{"code":-32000,"message":"Python 3.12+ not found on PATH"},"id":null}' >&2
    exit 1
fi

exec "$PYTHON" "${REPO_ROOT}/src/isomap/main.py" "$1"
