#!/usr/bin/env bash
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export PYTHONUTF8="${PYTHONUTF8:-1}"
export PYTHONIOENCODING="${PYTHONIOENCODING:-utf-8}"
export PYTHONDONTWRITEBYTECODE=1
source "$root/bin/agentlas-python-cache-boundary"
if ! agentlas_export_python_cache_boundary; then
  printf '%s\n' "ontology: could not establish a safe external Python cache directory." >&2
  exit 78
fi

root_native="$(agentlas_native_path "$root")"
path_sep="$(agentlas_path_sep)"

for candidate in "${HEPHAESTUS_PYTHON:-}" "$root/bin/python3" python3 python; do
  [[ -n "$candidate" ]] || continue
  if "$candidate" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)' >/dev/null 2>&1; then
    PYTHONPATH="$root_native${PYTHONPATH:+$path_sep$PYTHONPATH}" exec "$candidate" -m ontology "$@"
  fi
done

printf '%s\n' "ontology: Python 3.9+ not found. Re-run the Agentlas OS installer." >&2
exit 127
