#!/usr/bin/env bash
# model-dispatch.sh  -  which rung answers this call.
#
# The one place `prefs.global.modelRouting` turns into a rung. Every call site
# that may be routed asks here, so the policy has a single implementation and
# `/multi-agent:route-status` describes something real.
#
# Usage:
#   model-dispatch.sh <call-site> [--persona P] [--phase N] [--task-kind K]
#                                 [--default RUNG] [--task-id ID] [--complexity N]
#
# <call-site> is one of the `scope` members: subagent | bulk-read | delegate |
# research. stdout is a single rung NAME. Rung names are the contract; the model
# id behind one lives in cost-table.json and moves without a config edit.
#
# Exit is always 0 and stdout is always a usable answer. A router that can fail
# turns every call site into a place the run can die, for a feature that ships
# disabled; when anything is missing, unparseable or out of scope, the caller's
# default comes back unchanged.
#
# Two layers, and the difference is the safety argument the schema spells out:
#
#   Layer 1  an Anthropic rung. Reachable from every call site, because it
#            writes to a seam that already exists and opens no new network path.
#   Layer 2  the `free` rung: the multi-agent-mcp's verified free-model
#            chain. Reachable only where the pipeline makes the call itself -
#            bulk-read and delegate - and only with modelRouting.free.enabled.
#            Its caller must keep its default as the fallback, because the chain
#            answers ESCALATE_TO_CLAUDE whenever no free answer survives
#            verification. A subagent is dispatched by the HOST, so `free` and
#            every other non-Anthropic rung is refused there and the rule's next
#            rung answers instead.
#
# Strategies: manual keeps the rule's order; task-fit tries the cheapest rung
# first; cost-ceiling keeps the order until cost-budget-check.mjs reports the run
# at its warn threshold of budgetCeilingUsd, then tries the cheapest first.
#
# Learned order: with modelRouting.learned.enabled (ships false), the order the
# strategy produced is handed to route-learn.mjs choose, which reorders it from
# the PROMOTED policy for this call site, task kind and complexity band. Only
# a permutation of the rule's own candidates is taken, so learning can change
# which allowed rung is tried first and never adds one; the fable switch and
# the provider checks below still apply to whatever order comes back. No
# promoted policy, too few outcomes, or any failure leaves the order as it was.

set -uo pipefail

CALL_SITE="${1:-}"
shift || true

PERSONA=""; PHASE=""; TASK_KIND=""; DEFAULT_RUNG=""; COMPLEXITY=""; TASK_ID="${MULTI_AGENT_TASK_ID:-unknown}"
while [ $# -gt 0 ]; do
  case "$1" in
    --persona)   PERSONA="${2:-}"; shift 2 ;;
    --phase)     PHASE="${2:-}"; shift 2 ;;
    --task-kind) TASK_KIND="${2:-}"; shift 2 ;;
    --default)   DEFAULT_RUNG="${2:-}"; shift 2 ;;
    --task-id)   TASK_ID="${2:-}"; shift 2 ;;
    --complexity) COMPLEXITY="${2:-}"; shift 2 ;;
    *) shift ;;
  esac
done

emit() { printf '%s\n' "$1"; exit 0; }

[ -n "$DEFAULT_RUNG" ] || DEFAULT_RUNG="sonnet"

PREFS=""
for candidate in \
  "${MULTI_AGENT_PREFS:-}" \
  "$HOME/.claude/multi-agent-preferences.json" \
  "$HOME/.config/multi-agent-pipeline/multi-agent-preferences.json"
do
  [ -n "$candidate" ] && [ -f "$candidate" ] && { PREFS="$candidate"; break; }
done

# The fable rung exists only while modelFallback.fableEnabled is true, and it
# ships false. A caller whose default is fable - a command that runs without
# Phase 0, such as review - gets the documented resolution, opus, on every path
# out of here: routing off, out of scope, no rule, or nothing readable.
FABLE_ON=false
if [ -n "$PREFS" ] && command -v jq >/dev/null 2>&1; then
  FABLE_ON=$(jq -r '.global.modelFallback.fableEnabled // false' "$PREFS" 2>/dev/null || echo false)
fi
[ "$DEFAULT_RUNG" = "fable" ] && [ "$FABLE_ON" != "true" ] && DEFAULT_RUNG="opus"

case "$CALL_SITE" in
  subagent|bulk-read|delegate|research) ;;
  *) emit "$DEFAULT_RUNG" ;;
esac

command -v jq >/dev/null 2>&1 || emit "$DEFAULT_RUNG"
[ -n "$PREFS" ] || emit "$DEFAULT_RUNG"

ENABLED=$(jq -r '.global.modelRouting.enabled // false' "$PREFS" 2>/dev/null) || emit "$DEFAULT_RUNG"
[ "$ENABLED" = "true" ] || emit "$DEFAULT_RUNG"

# Out of scope is not a failure and not a warning. The user named the call sites
# routing may touch; the ones they left out keep their existing behaviour, which
# is the point of naming them.
IN_SCOPE=$(jq -r --arg cs "$CALL_SITE" \
  '((.global.modelRouting.scope // ["subagent"]) | index($cs)) != null' "$PREFS" 2>/dev/null)
[ "$IN_SCOPE" = "true" ] || emit "$DEFAULT_RUNG"

# First rule whose every stated condition matches. A `when` with three keys has
# to match on all three - the schema requires at least one, so an always-matching
# rule cannot be written by accident.
MATCH=$(jq -r \
  --arg persona "$PERSONA" --arg phase "$PHASE" --arg kind "$TASK_KIND" \
  '[ (.global.modelRouting.rules // [])[]
     | select(
         ((.when.persona  // null) as $p | $p == null or $p == $persona)
         and ((.when.phase   // null) as $h | $h == null or ($phase != "" and ($h | tostring) == $phase))
         and ((.when.taskKind // null) as $k | $k == null or $k == $kind)
       )
   ] | first | (.prefer // []) | join(" ")' "$PREFS" 2>/dev/null) || emit "$DEFAULT_RUNG"
[ "$MATCH" = "null" ] && MATCH=""

FREE_ON=$(jq -r '.global.modelRouting.free.enabled // false' "$PREFS" 2>/dev/null)
CANDIDATES="$MATCH"
case "$CALL_SITE" in
  bulk-read|delegate) [ "$FREE_ON" = "true" ] && CANDIDATES="free $MATCH" ;;
esac
[ -n "${CANDIDATES// /}" ] || emit "$DEFAULT_RUNG"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COST_TABLE="$HERE/../scripts/cost-table.json"
HOSTS_JSON="$HERE/../schemas/hosts.json"

# Which host this router is installed under, and therefore which rungs it can
# dispatch at all. Reading this from the registry rather than assuming one
# ladder is what keeps a rung another host does not offer from being handed
# back: a preference file is shared across hosts, so a rule naming a rung that
# exists on one of them is a normal thing to find here.
if [ -f "$HOSTS_JSON" ]; then
  # shellcheck source=./host.sh
  [ -f "$HERE/host.sh" ] && . "$HERE/host.sh"
  # Deliberately NOT defaulted to the first host. "I cannot tell which host I
  # am" and "I am the host the paths are authored against" are different
  # answers, and guessing the second hands back the one rung this gate exists
  # to refuse. An empty id takes the single-ladder rule below instead.
  HOST_ID=$(command -v ma_host_id >/dev/null 2>&1 && ma_host_id || echo "")
else
  HOST_ID=""
fi

STRATEGY=$(jq -r '.global.modelRouting.strategy // "manual"' "$PREFS" 2>/dev/null)
CHEAPEST_FIRST=false
STRATEGY_NOTE=""
case "$STRATEGY" in
  task-fit) CHEAPEST_FIRST=true; STRATEGY_NOTE="task-fit" ;;
  cost-ceiling)
    CEILING=$(jq -r '.global.modelRouting.budgetCeilingUsd // empty' "$PREFS" 2>/dev/null)
    if [ -n "$CEILING" ] && [ "$TASK_ID" != "unknown" ] && command -v node >/dev/null 2>&1 \
       && [ -f "$HERE/../scripts/cost-budget-check.mjs" ]; then
      node "$HERE/../scripts/cost-budget-check.mjs" --task-id "$TASK_ID" --max-usd "$CEILING" --enabled >/dev/null 2>&1
      case $? in
        10|11) CHEAPEST_FIRST=true; STRATEGY_NOTE="cost-ceiling reached" ;;
      esac
    fi
    ;;
esac

if [ "$CHEAPEST_FIRST" = "true" ] && [ -f "$COST_TABLE" ]; then
  CANDIDATES=$(
    jq -r --arg c "$CANDIDATES" '
      .prices as $p
    | ($c | split(" ") | map(select(length > 0)))
    | to_entries
    | sort_by([($p[.value].inPerMtok // 1e9), .key])
    | map(.value) | join(" ")' "$COST_TABLE" 2>/dev/null || printf '%s' "$CANDIDATES")
fi

words() { tr -s ' ' <<< "$1" | sed 's/^ //; s/ $//'; }
sorted_words() { tr ' ' '\n' <<< "$1" | grep -v '^$' | sort | tr '\n' ' '; }

LEARNED_ON=$(jq -r '.global.modelRouting.learned.enabled // false' "$PREFS" 2>/dev/null)
if [ "$LEARNED_ON" = "true" ] && command -v node >/dev/null 2>&1 \
   && [ -f "$HERE/../scripts/route-learn.mjs" ]; then
  LEARNED=$(node "$HERE/../scripts/route-learn.mjs" choose --call-site "$CALL_SITE" \
    --task-kind "$TASK_KIND" --complexity "$COMPLEXITY" --task-id "$TASK_ID" \
    --candidates "$CANDIDATES" 2>/dev/null) || LEARNED=""
  if [ -n "$LEARNED" ] && [ "$(sorted_words "$LEARNED")" = "$(sorted_words "$CANDIDATES")" ]; then
    [ "$(words "$LEARNED")" != "$(words "$CANDIDATES")" ] && STRATEGY_NOTE="learned"
    CANDIDATES="$LEARNED"
  fi
fi

# The fable rung answers only when the fable switch is on (FABLE_ON, read
# above). Routing is a policy over what is available; it is not a second way to
# turn a rung on, or `/multi-agent:fable-off` would stop meaning anything the
# moment a rule named fable.

record() {
  [ -x "$HERE/../scripts/log-metric.sh" ] || return 0
  local rec
  rec=$(jq -r 'if .global.modelRouting.recordDecisions == false then "false" else "true" end' "$PREFS" 2>/dev/null)
  [ "$rec" = "false" ] && return 0
  "$HERE/../scripts/log-metric.sh" "$TASK_ID" "${PHASE:-0}" model_routing.decision \
    call_site="$CALL_SITE" rung="$1" reason="$2" >/dev/null 2>&1 || true
}

for rung in $CANDIDATES; do
  if [ ! -f "$COST_TABLE" ]; then
    record "$rung" "no cost table; rung taken on trust"
    emit "$rung"
  fi
  PROVIDER=$(jq -r --arg r "$rung" '.prices[$r].provider // ""' "$COST_TABLE" 2>/dev/null)
  # A rung nobody priced is a typo in a config far more often than it is a new
  # model. Skipping it silently would route to the next one and leave the user
  # certain their rule applied.
  if [ -z "$PROVIDER" ]; then
    echo "model-dispatch: rung '$rung' is not in cost-table.json; skipping it" >&2
    continue
  fi
  if [ "$rung" = "fable" ] && [ "$FABLE_ON" != "true" ]; then
    echo "model-dispatch: rule prefers 'fable' but modelFallback.fableEnabled is false; skipping it" >&2
    continue
  fi
  if [ "$PROVIDER" = "free-chain" ]; then
    if [ "$FREE_ON" != "true" ]; then
      echo "model-dispatch: rule prefers 'free' but modelRouting.free.enabled is false (route-on --free); skipping it" >&2
      continue
    fi
    case "$CALL_SITE" in
      bulk-read|delegate)
        record "$rung" "free chain${STRATEGY_NOTE:+, $STRATEGY_NOTE}"
        emit "$rung" ;;
    esac
    echo "model-dispatch: rung 'free' is reachable only at bulk-read and delegate; a $CALL_SITE is dispatched by the host, skipping it" >&2
    continue
  fi
  # A rung is dispatchable here when THIS host offers it and the model behind it
  # is one this host speaks. The cost table prices a rung by name; what that
  # name runs differs per host, so the name alone cannot answer either question.
  if [ -n "$HOST_ID" ]; then
    RUNG_MODEL=$(jq -r --arg h "$HOST_ID" --arg r "$rung" \
      '.hosts[$h].models.rungs[$r].model // ""' "$HOSTS_JSON" 2>/dev/null)
    if [ -z "$RUNG_MODEL" ]; then
      echo "model-dispatch: rung '$rung' is not offered on $HOST_ID; skipping it" >&2
      continue
    fi
    RUNG_PROVIDER=$(jq -r --arg m "$RUNG_MODEL" \
      'first(.prices[] | select(.modelId == $m or .copilotModelId == $m) | .provider) // ""' \
      "$COST_TABLE" 2>/dev/null)
    if ! jq -e --arg h "$HOST_ID" --arg p "$RUNG_PROVIDER" \
      '(.hosts[$h].models.providers // []) | index($p) != null' "$HOSTS_JSON" >/dev/null 2>&1; then
      # The call site hands the rung to something that speaks one of this host's
      # own providers, so returning this one would produce a failed call rather
      # than a cheaper one.
      echo "model-dispatch: rung '$rung' runs $RUNG_MODEL ($RUNG_PROVIDER), which $HOST_ID does not dispatch; skipping it" >&2
      continue
    fi
  elif [ "$PROVIDER" != "anthropic" ]; then
    # No registry on this install: keep the single-ladder rule it shipped with.
    echo "model-dispatch: rung '$rung' is $PROVIDER and no call site dispatches to it; skipping it" >&2
    continue
  fi
  record "$rung" "rule matched${STRATEGY_NOTE:+, $STRATEGY_NOTE}"
  emit "$rung"
done

record "$DEFAULT_RUNG" "every preferred rung was unavailable"
emit "$DEFAULT_RUNG"
