#!/bin/sh
# digest-now.sh — on-demand "regenerate precursors + send the vault digests early".
#
# Sources the off-repo secrets env (same search order as digest.sh / sweep.sh), forces live
# vault writes FOR THIS PROCESS ONLY, then runs the
# on-demand engine (alexandria_vault.engine.digest_now) against this vault. It does
# NOT touch the scheduled sweep's launchd job, schedule, or env — it just reuses the same
# code path off the freshest vault.
#
# WHERE: run it on the always-on host (the secrets env + the `anthropic` package live there,
# not on the laptop).
#   On the host:   sh "$HOME/<vault>/Agent/scripts/daily-digest/digest-now.sh"
#   From laptop:   ssh <host> 'sh "$HOME/<vault>/Agent/scripts/daily-digest/digest-now.sh"'
#
# Flags pass straight through to digest_now.py:
#   --plan            preview only — no writes, no send, no state change
#   --keep-scheduled  send now AND still let the scheduled sweep fire (two copies that day)
set -e
ENVFILE=""
for f in "$ALEXANDRIA_ENV" "$HOME/Library/Application Support/Alexandria/alexandria.env" "$HOME/Alexandria-secrets/alexandria.env" "$HOME/.config/alexandria/alexandria.env"; do
  if [ -n "$f" ] && [ -f "$f" ]; then ENVFILE="$f"; break; fi
done
if [ -z "$ENVFILE" ]; then
  echo "digest-now.sh: no env file found. Create it with `alexandria secrets --set` (or set ALEXANDRIA_ENV)." >&2
  echo "  This must run on the always-on host — the secrets env + anthropic package live there, not on the laptop." >&2
  exit 1
fi
set -a; . "$ENVFILE"; set +a
# Force live writes for the precursor regen — THIS process only; the launchd sweep's env is
# untouched. (--plan still no-ops every write via the task-level plan guard, so a preview
# stays side-effect-free even with these set.)
export SWEEP_SHADOW=0
export SWEEP_AUTOFIX=1
DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
# The engine lives in the installed alexandria-vault package (docs/DEVAULT.md step 3),
# not in the vault: run it from $ALEXANDRIA_PYTHON if set (e.g. in alexandria.env), else
# the app venv the installer maintains, else whatever python3 has the package.
VAULT=$(CDPATH= cd -- "$DIR/../../.." && pwd)
APP_PY="$HOME/Library/Application Support/Alexandria/app/.venv/bin/python3"
if [ -n "$ALEXANDRIA_PYTHON" ]; then PY="$ALEXANDRIA_PYTHON"
elif [ -x "$APP_PY" ]; then PY="$APP_PY"
else PY="python3"; fi
exec "$PY" -m alexandria_vault.engine.digest_now --vault "$VAULT" "$@"
