#!/usr/bin/env sh
# Install RTFM optional extras into an isolated venv at
# ${CLAUDE_PLUGIN_DATA}/extras/venv/. Avoids polluting the user's
# system Python and bypasses PEP 668 because venv ≠ system site.
#
# Usage: rtfm-install-extras embeddings|gpu|reader|pdf|epub|office|mobi|ocr|xlsx|audio|all
#
#   embeddings  — FastEmbed ONNX (~85 MB), semantic + hybrid search.
#   gpu         — the same on an NVIDIA card (~2.5 GB), used by the indexing
#                 worker; queries stay on the processor. Replaces
#                 embeddings. Needs the NVIDIA driver.
#   pdf         — pdftext + pdfplumber (~60 MB), fast text extraction from
#                 most PDFs, ruled tables read row by row.
#   reader      — page reader (granite-docling, ~10 GB with torch), for scans
#                 and tables without rules. NVIDIA card, 6 GB of it. Models
#                 go to $HF_HOME, ~/.cache/huggingface by default. Linux.
#   epub        — ebooklib + beautifulsoup4 (~5 MB), EPUB reader.
#   office      — python-docx + odfpy + striprtf (~2 MB), DOCX / ODT / RTF.
#   mobi        — mobi + beautifulsoup4 (~2 MB), MOBI / AZW ebook reader.
#   ocr         — pytesseract + pypdfium2 + Pillow (~30 MB), OCR for
#                 scanned PDFs. Needs the tesseract binary on the host
#                 (apt install tesseract-ocr tesseract-ocr-<lang>).
#   xlsx        — openpyxl (~1 MB), XLSX spreadsheets.
#   audio       — mutagen (~1 MB), tags of MP3/FLAC/OGG/M4A/WAV/AIFF...
#                 (MIDI files need nothing.)
#   all         — everything above except gpu and reader.
#                 (~130 MB total.)

EXTRA="${1:-all}"
PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

case "$EXTRA" in
    gpu)    WITHOUT="Semantic search runs on the processor: use 'embeddings'." ;;
    reader) WITHOUT="Scans are read by tesseract: use 'ocr'." ;;
    *)      WITHOUT="" ;;
esac
if [ -n "$WITHOUT" ] && ! nvidia-smi >/dev/null 2>&1; then
    echo "rtfm-install-extras: no working NVIDIA driver (nvidia-smi)." >&2
    echo "  Nothing changed. $WITHOUT" >&2
    exit 1
fi

if [ -n "$CLAUDE_PLUGIN_DATA" ]; then
    DATA_DIR="$CLAUDE_PLUGIN_DATA"
else
    DATA_DIR="$HOME/.claude/plugins/data/rtfm"
fi

mkdir -p "$DATA_DIR/extras"
VENV="$DATA_DIR/extras/venv"

# Find a usable Python
BASE_PY=""
for PY in python3 python py; do
    if command -v "$PY" >/dev/null 2>&1; then
        BASE_PY="$PY"
        break
    fi
done

if [ -z "$BASE_PY" ]; then
    echo "rtfm-install-extras: Python 3.10+ not found on PATH" >&2
    exit 1
fi

# A venv built on another Python (the system's moved, e.g. 3.12 -> 3.14)
# still starts, but finds none of its packages: rebuild it. Packages asked
# for by name before are listed so they can be reinstalled.
if [ -f "$VENV/pyvenv.cfg" ]; then
    WANT=$("$BASE_PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])')
    HAVE=$(sed -n 's/^version *= *\([0-9]*\.[0-9]*\).*/\1/p' "$VENV/pyvenv.cfg")
    if [ -n "$HAVE" ] && [ "$HAVE" != "$WANT" ]; then
        BEFORE=$(for d in "$VENV"/lib/python*/site-packages/*.dist-info; do
                     [ -f "$d/REQUESTED" ] && basename "$d" | sed 's/-[0-9].*//'
                 done | tr '\n' ' ')
        echo "Extras venv was built on Python $HAVE, now $WANT: rebuilding it."
        [ -n "$BEFORE" ] && echo "  Installed before: $BEFORE"
        rm -rf "$VENV"
    fi
fi

if [ ! -d "$VENV" ]; then
    echo "Creating extras venv at $VENV ..."
    "$BASE_PY" -m venv "$VENV" || {
        echo "rtfm-install-extras: failed to create venv" >&2
        exit 1
    }
fi

PIP="$VENV/bin/pip"
[ -x "$PIP" ] || PIP="$VENV/Scripts/pip"
[ -x "$PIP" ] || {
    echo "rtfm-install-extras: pip not found in $VENV" >&2
    exit 1
}

# The GPU build ships the same modules as fastembed: upgrading one over the
# other would mix them, so whichever is installed is the one kept.
FASTEMBED="fastembed"
"$PIP" show --quiet fastembed-gpu >/dev/null 2>&1 && FASTEMBED="fastembed-gpu"

case "$EXTRA" in
    gpu)
        echo "Installing GPU embeddings (fastembed-gpu + CUDA libraries, ~2.5 GB) ..."
        "$PIP" uninstall --quiet --yes fastembed onnxruntime
        "$PIP" install --quiet --upgrade fastembed-gpu "onnxruntime-gpu[cuda,cudnn]" || {
            echo "GPU install failed, putting the processor version back ..." >&2
            "$PIP" uninstall --quiet --yes fastembed-gpu onnxruntime-gpu
            "$PIP" install --quiet --upgrade --force-reinstall --no-deps fastembed onnxruntime
            exit 1
        }
        ;;
    embeddings)
        echo "Installing embeddings extra (fastembed, ~85 MB) ..."
        "$PIP" install --quiet --upgrade "$FASTEMBED"
        ;;
    pdf)
        echo "Installing PDF extras (pdftext + pdfplumber, ~60 MB) ..."
        # Pillow < 13: fastembed (the embeddings extra) refuses 13, and pip
        # would otherwise raise it for the newest pdfplumber.
        "$PIP" install --quiet --upgrade pdftext pdfplumber "Pillow<13"
        ;;
    reader)
        READER="$DATA_DIR/extras/reader"
        MODELS="${HF_HOME:-$HOME/.cache/huggingface}"
        echo "Installing the page reader in $READER, its model in $MODELS (~10 GB in all) ..."
        mkdir -p "$READER" "$MODELS"
        rm -f "$READER/hf_home"
        # Exact versions: the readings were measured with these.
        set -- torch==2.15.0 torchvision==0.29.2 transformers==5.25.0 \
            accelerate==1.16.0 pillow==13.0.0 pypdfium2==5.15.2 \
            huggingface-hub==2.5.0 safetensors==0.8.0 tokenizers==0.23.3 \
            numpy==2.5.5
        if command -v uv >/dev/null 2>&1; then
            uv venv --quiet --clear --python "$(command -v "$BASE_PY")" "$READER/venv" &&
                uv pip install --quiet --python "$READER/venv/bin/python" "$@"
        else
            "$BASE_PY" -m venv --clear "$READER/venv" &&
                "$READER/venv/bin/pip" install --quiet "$@"
        fi && (cd "$PLUGIN_ROOT" && "$BASE_PY" -c "
from rtfm.parsers._reader import MODEL, REVISION
print(MODEL, REVISION)") > "$READER/model" &&
            HF_HOME="$MODELS" "$READER/venv/bin/python" -c "
import sys
from huggingface_hub import snapshot_download
name, revision = open(sys.argv[1]).read().split()
snapshot_download(name, revision=revision,
                  allow_patterns=['*.json', '*.jinja', '*.safetensors'])
" "$READER/model" && printf '%s\n' "$MODELS" > "$READER/hf_home"
        ;;
    epub)
        echo "Installing EPUB extras (ebooklib + beautifulsoup4, ~5 MB) ..."
        "$PIP" install --quiet --upgrade ebooklib beautifulsoup4
        ;;
    office)
        echo "Installing office extras (python-docx + odfpy + striprtf, ~2 MB) ..."
        "$PIP" install --quiet --upgrade python-docx odfpy striprtf
        ;;
    mobi)
        echo "Installing MOBI extras (mobi + beautifulsoup4, ~2 MB) ..."
        "$PIP" install --quiet --upgrade mobi beautifulsoup4
        ;;
    ocr)
        echo "Installing OCR extras (pytesseract + pypdfium2 + Pillow, ~30 MB) ..."
        echo "  Needs the tesseract binary on the host (apt install tesseract-ocr)."
        "$PIP" install --quiet --upgrade pytesseract pypdfium2 Pillow
        ;;
    xlsx)
        echo "Installing XLSX extras (openpyxl, ~1 MB) ..."
        "$PIP" install --quiet --upgrade openpyxl
        ;;
    audio)
        echo "Installing audio extras (mutagen, ~1 MB) ..."
        "$PIP" install --quiet --upgrade mutagen
        ;;
    all)
        echo "Installing everything except gpu and reader (embeddings + pdf + epub + office + mobi + ocr + xlsx + audio, ~130 MB) ..."
        "$PIP" install --quiet --upgrade \
            "$FASTEMBED" pdftext pdfplumber \
            ebooklib beautifulsoup4 \
            python-docx odfpy striprtf \
            mobi \
            pytesseract pypdfium2 Pillow \
            openpyxl \
            mutagen
        ;;
    *)
        echo "Unknown extra: $EXTRA (expected: embeddings, gpu, reader, pdf, epub, office, mobi, ocr, xlsx, audio, all)" >&2
        exit 1
        ;;
esac

STATUS=$?
if [ $STATUS -eq 0 ]; then
    echo "Done. Restart Claude Code for the new extras to be picked up."
else
    echo "Install failed with exit code $STATUS" >&2
fi
exit $STATUS
