#!/bin/bash
# ontoref — global entry point for the ontoref protocol CLI.
#
# Discovers project root by walking up from CWD looking for .ontology/.
# No per-project wrapper needed. Works from any subdirectory.
#
# Usage:
#   ontoref adr l
#   ontoref sync
#   ONTOREF_PROJECT_ROOT=/path/to/project ontoref adr l   # explicit override
#
# Install:
#   ln -sf /path/to/ontoref/install/ontoref-global ~/.local/bin/ontoref

set -euo pipefail

ONTOREF_ROOT="${ONTOREF_ROOT:-/Users/Akasha/Development/ontoref}"

if [[ ! -f "${ONTOREF_ROOT}/ontoref" ]]; then
  echo "ontoref: entry point not found at ${ONTOREF_ROOT}/ontoref" >&2
  echo "  Set ONTOREF_ROOT to the correct path." >&2
  exit 1
fi

# Walk up from CWD to find the nearest directory containing .ontology/
_find_project_root() {
  local dir
  dir="$(pwd)"
  while [[ "${dir}" != "/" ]]; do
    [[ -d "${dir}/.ontology" ]] && echo "${dir}" && return 0
    dir="$(dirname "${dir}")"
  done
  return 1
}

if [[ -z "${ONTOREF_PROJECT_ROOT:-}" ]]; then
  if ! ONTOREF_PROJECT_ROOT="$(_find_project_root)"; then
    echo "ontoref: no .ontology/ found from $(pwd) up to /" >&2
    echo "  Run from within a project that has .ontology/, or set ONTOREF_PROJECT_ROOT." >&2
    exit 1
  fi
fi

export ONTOREF_ROOT
export ONTOREF_PROJECT_ROOT

_paths="${ONTOREF_PROJECT_ROOT}:${ONTOREF_PROJECT_ROOT}/.ontology:${ONTOREF_PROJECT_ROOT}/adrs:${ONTOREF_ROOT}/adrs:${ONTOREF_ROOT}/ontology/schemas:${ONTOREF_ROOT}"
export NICKEL_IMPORT_PATH="${_paths}${NICKEL_IMPORT_PATH:+:${NICKEL_IMPORT_PATH}}"
unset _paths

export ONTOREF_CALLER="${ONTOREF_CALLER:-ontoref}"

exec "${ONTOREF_ROOT}/ontoref" "$@"
