#!/bin/sh
# Entry point for the wikitool CLI, so agents and people invoke it through one
# stable path on every platform:
#
#   tools/wikitool <command> [options]
#
# This is the POSIX half - Linux, macOS and Git Bash on Windows. PowerShell 7
# resolves the same string to tools/wikitool.ps1 first.
#
# Nothing here sets up an environment. tools/preflight.sh does that, once per
# checkout and again after every stack update: it records the tool paths in
# .wikitool-tools.json and creates tools/.venv. Until it has passed, this script
# stops with exit 42 and names it - the preflight is the one step that must not
# be skipped or improvised around (instructions/preflight.md).
set -eu
DIR=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P)
ROOT=$(dirname -- "$DIR")

# Both venv layouts: bin/ everywhere but Windows, Scripts\ there - which is also
# what a venv created by a native Windows Python looks like from Git Bash.
if [ -x "$DIR/.venv/bin/python" ]; then
  PY="$DIR/.venv/bin/python"
elif [ -f "$DIR/.venv/Scripts/python.exe" ]; then
  PY="$DIR/.venv/Scripts/python.exe"
else
  PY=""
fi

if [ -z "$PY" ] || ! grep -q '"complete": true' "$ROOT/.wikitool-tools.json" 2>/dev/null; then
  cat >&2 <<'EOF'
STOP - this checkout is not set up yet (or no longer after an update).
Run the preflight first; it checks what this computer has, records the tool
paths and creates tools/.venv:

  tools/preflight.sh

It exits 0 when everything is in place. If it exits 42, show its output to the
user as it is and wait - it says what to do. See instructions/preflight.md.
EOF
  exit 42
fi

# Do NOT cd into $DIR: that would resolve relative CLI arguments (e.g.
# --markdown "kb/Lint Report.md") against tools/ instead of the caller's cwd.
# Running a script puts its own directory on sys.path, which is how `chemenu`
# becomes importable without PYTHONPATH (whose separator differs on Windows).
exec "$PY" "$DIR/run_wikitool.py" "$@"
