#!/usr/bin/env bash
# Source this at the top of any skill's procedural shell scripts.
#
#   # shellcheck source=.agents/shared/skill-bootstrap.sh
#   source "$(dirname "$0")/../../shared/skill-bootstrap.sh"
#
# After sourcing, the following env vars are set for the rest of the
# process lifetime:
#   CSE_OPERATOR     short operator slug (jared, eric, ...)
#   CSE_TOOLD_BIN    resolved path to the signed cse-toold binary
#
# Behavior:
#   - This script is idempotent and safe to source multiple times.
#   - It prefers a plugin-local cse-toold binary and prepends that
#     directory to PATH for backward compatibility after bootstrap.

_cse_log() { printf '[skill-bootstrap] %s\n' "$*" >&2; }

if [ -n "${BASH_SOURCE[0]:-}" ]; then
  _cse_script_source="${BASH_SOURCE[0]}"
elif [ -n "${ZSH_VERSION:-}" ]; then
  _cse_script_source="$(eval 'printf %s "${(%):-%x}"')"
else
  _cse_script_source="$0"
fi
_cse_script_dir="$(cd "$(dirname "$_cse_script_source")" && pwd)"
_cse_plugin_root="$(cd "$_cse_script_dir/../.." && pwd)"

source "$_cse_script_dir/cse-toold-resolver.sh"

if ! _cse_export_toold_bin >/dev/null; then
  if [ "${_CSE_TOOLD_BOOTSTRAP_WARNED:-0}" != "1" ]; then
    _cse_log "cse-toold not found; install the plugin dependency, run npm install in plugins/cse-tools, or run ./scripts/cse-toold-dev-build.sh for local dev (fallback: target/debug/cse-toold)"
    _CSE_TOOLD_BOOTSTRAP_WARNED=1
  fi
fi

if [ "${_CSE_SKILL_BOOTSTRAP_DONE:-0}" = "1" ] && [ -x "${CSE_TOOLD_BIN:-}" ]; then
  unset _cse_log _cse_script_dir _cse_plugin_root
  unset -f \
    _cse_toold_path_prepend_once _cse_toold_root_list _cse_resolve_toold_bin \
    _cse_export_toold_bin _cse_toold_install_root _cse_toold_diagnostics
  return 0 2>/dev/null || exit 0
fi
_CSE_SKILL_BOOTSTRAP_DONE=1

# Operator identity for skills that route by operator (e.g. morning-digest).
# Decoupled from the removed voice system; defaults to the baseline operator.
export CSE_OPERATOR="${CSE_OPERATOR:-jared}"

unset _cse_log _cse_script_source _cse_script_dir _cse_plugin_root
unset _cse_toold_resolver_source _cse_toold_resolver_dir _cse_toold_default_root
unset -f \
  _cse_toold_path_prepend_once _cse_first_toold_platform_bin _cse_toold_root_list \
  _cse_resolve_toold_bin _cse_export_toold_bin _cse_toold_install_root _cse_toold_diagnostics
