#!/usr/bin/env bash
# route-state.sh  -  read and write prefs.global.modelRouting.
#
# Backs /multi-agent:route-on, route-off and route-status. Ships disabled and
# stays that way until someone turns it on; while `enabled` is false nothing in
# this file changes one dispatch.
#
# The `off` contract is borrowed from autopilot-off and for the same reason: it
# clears the ON STATE, never the rules. Turning routing back on must not re-ask
# for a configuration the user already gave.
#
# Usage:
#   route-state.sh status                       print the current policy and savings
#   route-state.sh on  [--strategy=S] [--scope=a,b] [--free [--allow-training]] [--no-free]
#   route-state.sh off
#   route-state.sh set-rules <file.json>        replace rules[] from a JSON array,
#                                               checked against the schema and cost table
#
# Exit codes:
#   0  -  done
#   2  -  bad usage
#   3  -  preferences missing/unparseable, or a scope value this refuses

set -uo pipefail

PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"

_MA_RS_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
if [ -f "$_MA_RS_HERE/user-facing.sh" ]; then . "$_MA_RS_HERE/user-facing.sh"; else . "$HOME/.claude/lib/user-facing.sh"; fi

# The scope values this accepts, spelled once. `host-session` is NOT here and
# must never be added: it would mean rewriting the host's base URL, which routes
# the user's whole session - work that has nothing to do with this pipeline
# included - through a third layer, breaks the subscription's auth model, and
# silently changes which model answers. The schema encodes the same list so a
# hand-edited preferences file is rejected too, rather than only this entry point.
ALLOWED_SCOPE="subagent bulk-read delegate research"

die() { echo "route-state: $1" >&2; exit "${2:-3}"; }

# A missing `jq` must not look like routing being off. Every read below would
# come back empty, `route-status` would report disabled, and a user with rules
# armed would be told there are none.
command -v jq >/dev/null 2>&1 || die "jq not found  -  cannot read or write preferences (install: brew install jq)"
[ -f "$PREFS" ] || die "preferences not found at $PREFS  -  run $(ma_command setup) first"
jq -e . "$PREFS" >/dev/null 2>&1 || die "$PREFS is not valid JSON  -  refusing to write over it"

ACTION="${1:-status}"; shift 2>/dev/null || true

COST_TABLE="$_MA_RS_HERE/../scripts/cost-table.json"
USAGE_LOG="${MCP_TOOLKIT_INDEX_DIR:-$HOME/.claude/logs/multi-agent-mcp/.index}/llm-usage.jsonl"

write_prefs() {
  local filter="$1"; shift
  local tmp
  tmp=$(mktemp) || die "mktemp failed"
  if ! jq "$@" "$filter" "$PREFS" > "$tmp"; then rm -f "$tmp"; die "jq failed  -  preferences left untouched"; fi
  jq -e . "$tmp" >/dev/null 2>&1 || { rm -f "$tmp"; die "produced invalid JSON  -  preferences left untouched"; }
  mv "$tmp" "$PREFS"
}

# Last seven days of the toolkit's usage logs (attended, and an unattended run's
# own under ~/.multi-agent-unattended): verified answers, cache hits and
# escalations, and what those tokens would have cost on haiku, the rung bulk-read
# and simple tasks fall back to. An estimate, and labelled as one.
free_savings() {
  local logs=() f
  for f in "$USAGE_LOG" "$HOME/.multi-agent-unattended/toolkit-index/llm-usage.jsonl"; do
    [ -f "$f" ] && logs+=("$f")
  done
  if [ "${#logs[@]}" -eq 0 ]; then
    echo "savings: no free-model task recorded yet ($USAGE_LOG)"
    return 0
  fi
  local since
  since=$(( $(date +%s) - 7 * 86400 ))
  jq -rs --argjson since "$since" --slurpfile ct "$COST_TABLE" '
      map(select((.ts | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601? // 0) >= $since))
    | ($ct[0].prices.haiku // {inPerMtok: 0.5, outPerMtok: 2.5}) as $h
    | {
        n: length,
        ok: (map(select(.ok and (.cached | not))) | length),
        cached: (map(select(.ok and .cached)) | length),
        esc: (map(select(.ok | not)) | length),
        pin: (map(.prompt_tokens // 0) | add // 0),
        pout: (map(.completion_tokens // 0) | add // 0),
        by: (map(select(.ok and .provider)) | group_by(.provider) | map("\(.[0].provider) \(length)") | join(", "))
      }
    | . + {usd: ((.pin * $h.inPerMtok + .pout * $h.outPerMtok) / 1000000)}
    | "savings (7 days): \(.n) task(s), \(.ok) answered free and verified, \(.cached) from cache, \(.esc) handed back to Claude\n"
      + "  tokens kept off Claude: \(.pin) in + \(.pout) out  (~$\(.usd * 100 | round / 100) at haiku rates, an estimate)"
      + (if .by != "" then "\n  by provider: \(.by)" else "" end)
  ' "${logs[@]}" 2>/dev/null || echo "savings: the usage log could not be read"
}

# What the toolkit can reach, without a single network call: configured
# providers and where their keys come from. Names only, never values.
free_providers() {
  local tl="$_MA_RS_HERE/toolkit-llm.sh"
  [ -f "$tl" ] || tl="$HOME/.claude/lib/toolkit-llm.sh"
  [ -f "$tl" ] || { echo "free chain: toolkit-llm.sh is not installed"; return 1; }
  # shellcheck source=/dev/null
  . "$tl"
  local out
  out=$(ma_toolkit_llm providers ${1:+--allow-training} 2>/dev/null) || { echo "free chain: the multi-agent-mcp CLI could not be run (node and npx are needed)"; return 1; }
  jq -r '
      "free chain: \(.configured) provider(s) usable under the \(.data_policy) data policy",
      (.providers[] | "  \(if .configured and .allowed_by_policy then "ready  " elif .configured then "policy " else "missing" end) \(.id)\(if .key_source then " (" + .key_source + ")" else "" end)\(if (.configured | not) then "  -  " + .setup else "" end)")
    ' <<< "$out"
  [ "$(jq -r '.configured' <<< "$out")" -gt 0 ]
}

case "$ACTION" in
  status)
    ENABLED=$(jq -r '.global.modelRouting.enabled // false' "$PREFS")
    STRATEGY=$(jq -r '.global.modelRouting.strategy // "manual"' "$PREFS")
    SCOPE=$(jq -r '(.global.modelRouting.scope // ["subagent"]) | join(", ")' "$PREFS")
    NRULES=$(jq -r '(.global.modelRouting.rules // []) | length' "$PREFS")
    CEIL=$(jq -r '.global.modelRouting.budgetCeilingUsd // "none"' "$PREFS")
    REC=$(jq -r 'if .global.modelRouting.recordDecisions == false then "false" else "true" end' "$PREFS")

    FREE=$(jq -r '.global.modelRouting.free.enabled // false' "$PREFS")
    TRAIN=$(jq -r '.global.modelRouting.free.allowTraining // false' "$PREFS")

    echo "routing:   $ENABLED"
    echo "strategy:  $STRATEGY"
    echo "scope:     $SCOPE"
    echo "rules:     $NRULES"
    echo "free:      $FREE$([ "$FREE" = "true" ] && echo " (data policy: $([ "$TRAIN" = "true" ] && echo any || echo no-training))")"
    echo "ceiling:   $CEIL"
    echo "decisions: $REC"
    echo "learned:   $(jq -r '.global.modelRouting.learned.enabled // false' "$PREFS")"
    echo ""

    if [ "$ENABLED" != "true" ]; then
      echo "Disabled. Rules are stored but read by nothing; dispatch is unchanged."
      [ "$NRULES" -gt 0 ] && echo "route-on turns these $NRULES rule(s) back on without re-asking."
      exit 0
    fi

    if [ "$NRULES" -eq 0 ] && [ "$FREE" != "true" ]; then
      echo "Armed with no rules. Nothing matches, so nothing is routed  -  this is a"
      echo "configuration state, not an error."
    elif [ "$NRULES" -gt 0 ]; then
      jq -r '(.global.modelRouting.rules // [])[] |
        "  when " + ([.when | to_entries[] | "\(.key)=\(.value)"] | join(" ")) +
        "  ->  " + (.prefer | join(" > "))' "$PREFS"
    fi

    if [ "$FREE" = "true" ]; then
      echo "  free chain first at: bulk-read, delegate (Anthropic default when it escalates)"
      echo ""
      free_savings
    fi

    echo ""
    # The limit is printed every time rather than documented once, because the
    # question it answers ("routing is on, why is the reviewer still on Opus")
    # otherwise arrives days later as a bug report.
    echo "Honest limit: on Claude Code a subagent cannot be sent to a non-Anthropic"
    echo "model  -  subagent dispatch belongs to the host. Phase 1/2/3 personas stay"
    echo "inside the Anthropic ladder whatever the rules say. Free models answer only"
    echo "where this pipeline makes the call itself (bulk-read, delegate), only after"
    echo "the toolkit verified the answer against its source, and Claude takes over"
    echo "whenever none passes."
    ;;

  on)
    STRATEGY="manual"; SCOPE_ARG=""; FREE_ARG=""; TRAIN_ARG=false
    for arg in "$@"; do
      case "$arg" in
        --strategy=*) STRATEGY="${arg#*=}" ;;
        --scope=*)    SCOPE_ARG="${arg#*=}" ;;
        --free)       FREE_ARG=on ;;
        --no-free)    FREE_ARG=off ;;
        --allow-training) TRAIN_ARG=true ;;
        *) die "unknown option: $arg" 2 ;;
      esac
    done
    [ "$TRAIN_ARG" = "true" ] && [ "$FREE_ARG" != "on" ] && die "--allow-training only goes with --free" 2
    case "$STRATEGY" in
      manual|task-fit|cost-ceiling) ;;
      *) die "strategy must be manual, task-fit or cost-ceiling (got '$STRATEGY')" 2 ;;
    esac

    if [ -n "$SCOPE_ARG" ]; then
      SCOPE_JSON="[]"
      IFS=',' read -r -a parts <<< "$SCOPE_ARG"
      for one in "${parts[@]}"; do
        one="${one// /}"
        # shellcheck disable=SC2076
        case " $ALLOWED_SCOPE " in
          *" $one "*) ;;
          *) die "scope '$one' is not allowed (allowed: $ALLOWED_SCOPE). 'host-session' is refused by design: it would route the whole session, not this pipeline's calls." ;;
        esac
        SCOPE_JSON=$(jq -c --arg s "$one" '. + [$s]' <<< "$SCOPE_JSON")
      done
      write_prefs '
          .global.modelRouting //= {}
        | .global.modelRouting.enabled = true
        | .global.modelRouting.strategy = $st
        | .global.modelRouting.scope = ($sc | fromjson)
      ' --arg st "$STRATEGY" --arg sc "$SCOPE_JSON"
    else
      write_prefs '
          .global.modelRouting //= {}
        | .global.modelRouting.enabled = true
        | .global.modelRouting.strategy = $st
        | .global.modelRouting.scope //= ["subagent"]
      ' --arg st "$STRATEGY"
    fi
    if [ "$FREE_ARG" = "on" ]; then
      write_prefs '
          .global.modelRouting.free = {enabled: true, allowTraining: $tr}
        | .global.modelRouting.scope = (((.global.modelRouting.scope // ["subagent"]) + ["bulk-read", "delegate"]) | unique)
      ' --argjson tr "$TRAIN_ARG"
      echo "free chain enabled at bulk-read and delegate (data policy: $([ "$TRAIN_ARG" = "true" ] && echo any || echo no-training))"
      TRAIN_FLAG=""
      [ "$TRAIN_ARG" = "true" ] && TRAIN_FLAG=1
      if ! free_providers "$TRAIN_FLAG"; then
        echo ""
        echo "No free provider is usable yet, so every task still runs on Claude. Add one key"
        echo "(free at https://console.groq.com/keys) with $(ma_command setup), or from a shell:"
        echo "  bash \"\$HOME/.claude/lib/credential-store.sh\" set llm-groq -    (paste the key, then Ctrl-D)"
        echo "or export GROQ_API_KEY for the server, then run $(ma_command route-status)."
      fi
      echo ""
    elif [ "$FREE_ARG" = "off" ]; then
      write_prefs '.global.modelRouting.free.enabled = false'
      echo "free chain disabled; Anthropic rungs only"
    fi
    echo "routing enabled (strategy: $STRATEGY)"
    exec "$0" status
    ;;

  off)
    # Rules survive on purpose. Clearing them here would make route-off a
    # destructive action wearing the name of a toggle.
    write_prefs '.global.modelRouting //= {} | .global.modelRouting.enabled = false'
    echo "routing disabled. Rules kept  -  route-on restores this configuration as it is."
    ;;

  set-rules)
    FILE="${1:-}"
    [ -n "$FILE" ] || die "set-rules needs a JSON file containing an array of rules" 2
    [ -f "$FILE" ] || die "no such file: $FILE" 2
    jq -e 'type == "array"' "$FILE" >/dev/null 2>&1 || die "$FILE must contain a JSON ARRAY of rules" 2
    # The schema's rule shape, enforced here so a hand-written file cannot store
    # a rule that dispatch silently skips: when has 1-3 known keys with valid
    # values, prefer is a non-empty list of rungs the cost table prices.
    RUNGS=$(jq -c '.prices | keys' "$COST_TABLE" 2>/dev/null || echo '[]')
    BAD=$(jq -r --argjson rungs "$RUNGS" '
        to_entries[] | .key as $i | .value as $r
      | if ($r | type) != "object" then "rule \($i): not an object"
        elif (($r | keys) - ["when", "prefer"]) != [] then "rule \($i): unknown key(s) \((($r | keys) - ["when", "prefer"]) | join(", "))"
        elif ($r.when | type) != "object" or ($r.when | length) == 0 then "rule \($i): when needs persona, phase or taskKind"
        elif (($r.when | keys) - ["persona", "phase", "taskKind"]) != [] then "rule \($i): when has unknown key(s) \((($r.when | keys) - ["persona", "phase", "taskKind"]) | join(", "))"
        elif ($r.when.persona != null and ($r.when.persona | type) != "string") then "rule \($i): persona must be a string"
        elif ($r.when.phase != null and (($r.when.phase | type) != "number" or $r.when.phase < 0 or $r.when.phase > 5 or ($r.when.phase | floor) != $r.when.phase)) then "rule \($i): phase must be an integer 0-5"
        elif ($r.when.taskKind != null and ([$r.when.taskKind] | inside(["bugfix", "feature", "refactor", "chore", "component"]) | not)) then "rule \($i): taskKind must be bugfix, feature, refactor, chore or component"
        elif ($r.prefer | type) != "array" or ($r.prefer | length) == 0 then "rule \($i): prefer needs at least one rung"
        elif ([$r.prefer[] | select((type != "string") or (. as $x | $rungs | index($x) | not))] | length) > 0 then "rule \($i): unknown rung(s) \([$r.prefer[] | select((type != "string") or (. as $x | $rungs | index($x) | not))] | map(tostring) | join(", ")) (known: \($rungs | join(", ")))"
        else empty end' "$FILE" 2>/dev/null)
    [ -z "$BAD" ] || die "$(printf 'rules rejected, nothing written:\n%s' "$BAD")" 2
    write_prefs '.global.modelRouting //= {} | .global.modelRouting.rules = $r' --slurpfile _ignore /dev/null --argjson r "$(cat "$FILE")"
    echo "rules replaced: $(jq -r 'length' "$FILE")"
    ;;

  *)
    echo "usage: route-state.sh [status|on|off|set-rules <file>]" >&2
    exit 2
    ;;
esac
