#!/usr/bin/env bash
# paper-monitor-ingest-dir — watch a directory for new PDFs and ingest
# them into the precis-mcp store.
#
# Prefers the shared workspace venv at `pips/.venv`, which since the
# single-venv migration carries the `[paper]` extras (acatome-extract
# + sentence-transformers) via the workspace root's `dev` dependency
# group. Falls back to a legacy per-package `.venv` and finally to
# `uv run` so the script keeps working on older checkouts.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PKG_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
WORKSPACE_ROOT="$(cd "$PKG_DIR/../.." && pwd)"
WORKSPACE_PY="$WORKSPACE_ROOT/.venv/bin/python"
PKG_VENV_PY="$PKG_DIR/.venv/bin/python"

: "${PRECIS_DATABASE_URL:=postgresql://acatome:acatome@127.0.0.1:5432/precis}"
: "${PRECIS_EMBEDDER:=bge-m3}"
export PRECIS_DATABASE_URL PRECIS_EMBEDDER

# 1. Shared workspace venv (current layout).
if [[ -x "$WORKSPACE_PY" ]]; then
    exec "$WORKSPACE_PY" "$SCRIPT_DIR/_paper_monitor_ingest_dir.py" "$@"
fi

# 2. Legacy per-package venv (pre-single-venv migration).
if [[ -x "$PKG_VENV_PY" ]]; then
    exec "$PKG_VENV_PY" "$SCRIPT_DIR/_paper_monitor_ingest_dir.py" "$@"
fi

# 3. Last resort: let uv sync the workspace on demand. Slow but
# always works from a fresh clone.
exec uv run --project "$WORKSPACE_ROOT" python \
    "$SCRIPT_DIR/_paper_monitor_ingest_dir.py" "$@"
