#!/usr/bin/env bash
# venv entrypoint wrapper for this skill.
#
# Runs the skill's Python entrypoint (named <this-script>.py, in this scripts/
# directory) inside an isolated virtualenv, installing the skill's
# requirements.txt on first run and whenever it changes. All command-line
# arguments are forwarded to the Python script, so the script's stdout stays
# clean (the wrapper writes progress to stderr only).
#
#   scripts/seedance -t "a daisy field, camera pushing in"   # runs scripts/seedance.py
#   scripts/seedance test_seedance.py                          # runs another script in this dir
#
# Override the venv location with SKILL_VENV_DIR=<path>.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REQ_FILE="$SKILL_DIR/requirements.txt"
VENV_DIR="${SKILL_VENV_DIR:-$SKILL_DIR/.venv}"
VENV_PY="$VENV_DIR/bin/python"
STAMP="$VENV_DIR/.requirements.stamp"

die() { echo "ERROR (wrapper): $*" >&2; exit 1; }

# --- pick a Python interpreter ----------------------------------------------
# Prefer 3.11/3.12: some OpenAI-style proxies serve a TLS chain whose
# intermediate CA lacks the keyUsage extension, which CPython 3.14 rejects.
# 3.11 accepts it. Falls back to any python3 >= 3.7.
pick_python() {
    for cand in python3.11 python3.12 python3.13 python3 python; do
        command -v "$cand" >/dev/null 2>&1 || continue
        "$cand" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 7) else 1)' \
            >/dev/null 2>&1 || continue
        printf '%s\n' "$cand"
        return 0
    done
    return 1
}

# Bootstrap pip into an existing (pip-less) venv, e.g. when python3.11-venv /
# ensurepip is not installed. Needs network for the get-pip.py fallback.
bootstrap_pip() {
    "$VENV_PY" -m ensurepip --upgrade >/dev/null 2>&1 && return 0
    local gp="$VENV_DIR/get-pip.py"
    echo "[wrapper] ensurepip unavailable; fetching get-pip.py" >&2
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL https://bootstrap.pypa.io/get-pip.py -o "$gp" || return 1
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$gp" https://bootstrap.pypa.io/get-pip.py || return 1
    else
        "$VENV_PY" -c "import urllib.request; urllib.request.urlretrieve('https://bootstrap.pypa.io/get-pip.py', '$gp')" || return 1
    fi
    "$VENV_PY" "$gp" >/dev/null 2>&1; local rc=$?
    rm -f "$gp"
    [ $rc -eq 0 ]
}

# --- ensure venv exists with a working pip ---------------------------------
if [ ! -x "$VENV_PY" ]; then
    echo "[wrapper] creating virtualenv at $VENV_DIR" >&2
    PYBIN="$(pick_python)" || die "no suitable Python interpreter found (need >= 3.7)"
    echo "[wrapper] using interpreter: $PYBIN" >&2
    if ! "$PYBIN" -m venv "$VENV_DIR" 1>&2; then
        # venv module present but ensurepip missing (e.g. no python3.11-venv).
        rm -rf "$VENV_DIR"
        "$PYBIN" -m venv --without-pip "$VENV_DIR" 1>&2 \
            || die "venv creation failed (python: $PYBIN)"
    fi
fi

if ! "$VENV_PY" -m pip --version >/dev/null 2>&1; then
    bootstrap_pip || die "could not bootstrap pip into $VENV_DIR (install python3-venv / ensurepip, or ensure network access)"
fi

# --- (re)install deps when needed -------------------------------------------
need_install=0
[ -f "$STAMP" ] || need_install=1
if [ -f "$REQ_FILE" ] && ! cmp -s "$REQ_FILE" "$STAMP" 2>/dev/null; then
    need_install=1
fi

if [ "$need_install" -eq 1 ]; then
    if [ -f "$REQ_FILE" ]; then
        echo "[wrapper] installing dependencies from $REQ_FILE" >&2
        if "$VENV_PY" -m pip install --disable-pip-version-check --no-input -r "$REQ_FILE" >&2; then
            cp "$REQ_FILE" "$STAMP"
        else
            echo "[wrapper] WARNING: dependency installation failed; continuing in case the script does not need them" >&2
        fi
    else
        : > "$STAMP"   # no requirements.txt — record so we don't retry every run
    fi
fi

# --- resolve target script --------------------------------------------------
DEFAULT_TARGET="$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}").py"
if [ $# -gt 0 ] && [ "${1##*.}" = "py" ] && [ -f "$SCRIPT_DIR/$1" ]; then
    TARGET="$SCRIPT_DIR/$1"; shift
else
    TARGET="$DEFAULT_TARGET"
fi
[ -f "$TARGET" ] || die "target script not found: $TARGET"

exec "$VENV_PY" "$TARGET" "$@"
