#!/usr/bin/env bash
# user-facing.sh  -  the two things a line a person READS has to resolve.
#
# A shipped script has two audiences. Log lines, state values and identifiers
# are read by machines and stay English. Everything else is read by whoever ran
# the command, and that half answers to the same preference the rest of the
# pipeline answers to - so the resolution lives here once instead of in every
# script that prints a sentence.
#
#   ma_output_lang              # "en" or "tr", from prefs.global.outputLanguage
#   ma_command <sub> [root]     # the subcommand, spelled the way this host spells it
#
# Usage:
#   . "$(dirname "${BASH_SOURCE[0]}")/user-facing.sh"
#   LANG_CODE=$(ma_output_lang)
#
# English is the default and the fallback: an absent preferences file, an
# unreadable one, and a language this pipeline does not carry all resolve to
# `en` rather than to whichever value happened to be written.

# $MULTI_AGENT_PREFS is honoured so a test can point the resolution at a fixture
# without writing to the developer's own preferences.
ma_prefs_file() {
  printf '%s\n' "${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
}

ma_output_lang() {
  local prefs lang
  prefs=$(ma_prefs_file)
  if [ -r "$prefs" ]; then
    if command -v jq >/dev/null 2>&1; then
      lang=$(jq -r '.global.outputLanguage // "en"' "$prefs" 2>/dev/null)
    else
      # jq is absent on a machine that has not finished onboarding, and the
      # scripts that run there - keychain and SSH setup - are exactly the ones
      # that run first. A one-key read does not need a JSON parser.
      lang=$(sed -n 's/.*"outputLanguage"[[:space:]]*:[[:space:]]*"\([a-zA-Z-]*\)".*/\1/p' "$prefs" 2>/dev/null | head -1)
    fi
  fi
  case "$lang" in
    tr | en) ;;
    *) lang=en ;;
  esac
  printf '%s\n' "$lang"
}

# The three CLIs spell the same command three ways, and the tree this file was
# sourced from is the one in front of the user. A line that names a command
# names the one this machine can actually type.
ma_command() { # $1 = subcommand, e.g. setup; $2 = host root, defaults to this file's
  local sub="$1" root="${2:-}"
  [ -n "$root" ] || root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)
  case "${root##*/}" in
    .copilot) printf '/multi-agent-%s\n' "$sub" ;;
    .codex) printf 'multi-agent %s\n' "$sub" ;;
    *) printf '/multi-agent:%s\n' "$sub" ;;
  esac
}
