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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export PYTHONUTF8="${PYTHONUTF8:-1}"
export PYTHONIOENCODING="${PYTHONIOENCODING:-utf-8}"
export PYTHONDONTWRITEBYTECODE=1
if ! source "$root/bin/agentlas-python-cache-boundary" \
  || ! agentlas_export_python_cache_boundary; then
  case " ${*:-} " in
    *" --host opencode "*|*" --host raw "*) ;;
    *) printf '{}\n' ;;
  esac
  exit 0
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
    if PYTHONPATH="$root_native${PYTHONPATH:+$path_sep$PYTHONPATH}" "$candidate" -m agentlas_cloud.memory_hook "$@"; then
      exit 0
    fi
    break
  fi
done

# Hooks must never block the host when Python or the local runtime is
# unavailable. Host-native policy remains active; only supplemental recall is
# skipped.
case " ${*:-} " in
  *" --host opencode "*|*" --host raw "*) ;;
  *) printf '{}\n' ;;
esac
exit 0
