#!/usr/bin/env bash
# TeamBot runner - self-contained, no pip from PyPI
# Downloads Cython-compiled wheel from teambot.samai.cc
set -euo pipefail
TEAMBOT_VERSION="1.52.6"
TEAMBOT_DIR="${HOME}/.teambot/runtime"
VENV_DIR="${TEAMBOT_DIR}/venv"
BASE_URL="https://teambot.samai.cc/downloads"

# Check Python
for cmd in python3.14 python3.13 python3.12 python3.11 python3.10 python3 python; do
    if command -v "$cmd" &>/dev/null; then
        PY="$cmd"; break
    fi
done
[ -z "${PY:-}" ] && { echo "teambot: Python 3.10+ required" >&2; exit 1; }

# Create venv if needed
if [ ! -d "$VENV_DIR" ]; then
    "$PY" -m venv "$VENV_DIR" 2>/dev/null || "$PY" -m venv --without-pip "$VENV_DIR"
fi

# Download and install wheel from teambot.samai.cc (NOT PyPI)
MARKER="$VENV_DIR/.teambot_version"
if [ ! -f "$MARKER" ] || [ "$(cat "$MARKER")" != "$TEAMBOT_VERSION" ]; then
    echo "Installing teambot v$TEAMBOT_VERSION from teambot.samai.cc ..."
    WHL_NAME="$(curl -fsSL "$BASE_URL/" 2>/dev/null | grep -oP 'teambot_ai-[^"]+\.whl' | head -1 || true)"
    if [ -n "$WHL_NAME" ]; then
        TMP_WHL="$(mktemp -t teambot-whl-XXXXXX)"
        curl -fSL --retry 3 --retry-delay 2 -o "$TMP_WHL" "$BASE_URL/$WHL_NAME"
        "$VENV_DIR/bin/pip" install --no-deps --no-index "$TMP_WHL" 2>/dev/null || \
        "$VENV_DIR/bin/pip" install "$TMP_WHL" 2>/dev/null || true
        rm -f "$TMP_WHL"
        echo "$TEAMBOT_VERSION" > "$MARKER"
    fi
fi

# Run teambot
exec "$VENV_DIR/bin/python" -m teambot_ai "$@"
