#!/usr/bin/env bash
# host.sh  -  which host a shell script is running under, and what the registry
# says about it.
#
# The mjs side is pipeline/lib/host.mjs and reads the same file. Source this
# rather than matching a host name: `pipeline/schemas/hosts.json` is the single
# source, and a script that compares `$HOST` to a literal is a script that has
# to be edited again when a host is added.
#
# Usage:
#   . "$(dirname "${BASH_SOURCE[0]}")/host.sh"
#   id=$(ma_host_id)                      # a host id, or empty off an install
#   ma_host_has_provider anthropic && ...
#
# Every function answers from the registry that shipped with THIS install, so a
# script copied into another host's tree answers for that host. Without jq there
# is no answer at all rather than a wrong one: callers treat an empty answer the
# way they treat a missing preference.

# The registry, resolved from this file's own location so it works in the repo
# (pipeline/lib -> pipeline/schemas) and in an install (<root>/lib -> <root>/schemas).
ma_host_registry() {
  printf '%s\n' "$(cd "$(dirname "${BASH_SOURCE[0]}")/../schemas" 2>/dev/null && pwd)/hosts.json"
}

# The host whose tree this file sits in, or empty from a repo checkout.
ma_host_id() {
  local reg seg
  reg=$(ma_host_registry)
  [ -f "$reg" ] || return 0
  command -v jq >/dev/null 2>&1 || return 0
  seg=$(basename "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)")
  jq -r --arg seg "$seg" \
    '[.hosts | to_entries[] | select(.value.detect.rootSegment == $seg) | .key][0] // ""' \
    "$reg" 2>/dev/null || true
}

# True when this host dispatches to the named provider.
ma_host_has_provider() {
  local reg id
  reg=$(ma_host_registry)
  id=$(ma_host_id)
  [ -f "$reg" ] || return 1
  command -v jq >/dev/null 2>&1 || return 1
  [ -n "$id" ] || id=$(jq -r '.order[0]' "$reg" 2>/dev/null)
  jq -e --arg id "$id" --arg p "$1" \
    '(.hosts[$id].models.providers // []) | index($p) != null' "$reg" >/dev/null 2>&1
}
