#!/bin/bash
# algebench launcher — auto-creates venv on first run, then starts the server.

DIR="$(cd "$(dirname "$0")" && pwd)"
VENV="$DIR/.venv"

# Provision .venv on first use. Prefer `uv` so the venv is built on a native
# CPython (arm64 on Apple Silicon), pinned by .python-version. Bare
# `python3 -m venv` picks whatever python3 is first on PATH — often the x86
# Homebrew build on Apple Silicon, which runs under Rosetta and roughly halves
# sympy throughput (issue #388). Falls back to python3 if uv is unavailable.
ensure_venv() {
    [ -d "$VENV" ] && return 0
    echo "Setting up virtual environment (first run only)..."
    if command -v uv >/dev/null 2>&1; then
        PYVER="$(cat "$DIR/.python-version" 2>/dev/null || echo 3.13)"
        # only-managed forces a uv-managed CPython, which always matches the host
        # arch (arm64 on Apple Silicon) — avoids selecting an x86 Homebrew python.
        uv venv --python "$PYVER" --python-preference only-managed "$VENV"
        uv pip install --python "$VENV/bin/python3" -r "$DIR/requirements.txt"
    else
        echo "⚠️  uv not found — using 'python3 -m venv' (may be x86/Rosetta on Apple Silicon; see issue #388)."
        python3 -m venv "$VENV"
        "$VENV/bin/pip" install -r "$DIR/requirements.txt"
    fi
}

if [ "$1" = "--update" ]; then
    shift
    echo "🔍 Checking for latest gemini-live-tools..."
    LATEST=$(git ls-remote --tags https://github.com/ibenian/gemini-live-tools.git \
        | grep -v '\^{}' | awk '{print $2}' | sed 's|refs/tags/||' | sort -V | tail -1)
    if [ -n "$LATEST" ]; then
        CURRENT=$(grep 'gemini-live-tools' "$DIR/requirements.txt" | grep -o '@v[^#]*' | tr -d '@')
        if [ "$CURRENT" != "$LATEST" ]; then
            echo "⬆️  Updating gemini-live-tools $CURRENT → $LATEST"
            sed -i '' "s|gemini-live-tools\.git@[^#]*|gemini-live-tools.git@$LATEST|" "$DIR/requirements.txt"
        else
            echo "✅ gemini-live-tools already at $LATEST"
        fi
    else
        echo "⚠️  Could not fetch latest gemini-live-tools tag, skipping version update"
    fi
    if [ ! -d "$VENV" ]; then
        # No venv yet — a fresh provision already installs the latest deps.
        ensure_venv
    else
        echo "📦 Updating dependencies..."
        if command -v uv >/dev/null 2>&1; then
            uv pip install --python "$VENV/bin/python3" --upgrade -r "$DIR/requirements.txt"
        else
            "$VENV/bin/pip" install --upgrade -r "$DIR/requirements.txt"
        fi
    fi
    echo "✓ Update complete"
    exit 0
fi

ensure_venv

# Load gitignored secrets if present. Format: KEY=VALUE per line (shell syntax).
# Does not override values already set in the parent environment.
if [ -f "$DIR/.env.local" ]; then
    set -a
    . "$DIR/.env.local"
    set +a
fi

export PYTHONPATH="${DIR}${PYTHONPATH:+:$PYTHONPATH}"
exec "$VENV/bin/python3" "$DIR/backend/server.py" "$@"
