#!/usr/bin/env bash
# roundtable — a council of frontier models (a Frontier Infra project)
#
# Portable subcommand dispatcher. Targets macOS bash 3.2 + Linux.
# Resolves its own real directory without relying on GNU `readlink -f`.
#
#   roundtable "question"            ask the council (default)
#   roundtable ask "question" ...    same, explicit
#   roundtable auth|models|heads|doctor|config|version|update
#   roundtable mcp ...               MCP server (lib/mcp.py)
#   roundtable install ...           harness auto-wire (lib/install.sh)

# ── resolve the real script dir (follow symlinks, portable) ────────────────
SOURCE="${BASH_SOURCE[0]:-$0}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  case "$SOURCE" in /*) ;; *) SOURCE="$DIR/$SOURCE" ;; esac
done
BINDIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
LIBDIR="$BINDIR/../lib"
[ -d "$LIBDIR" ] && LIBDIR="$(cd -P "$LIBDIR" >/dev/null 2>&1 && pwd)"

RT_CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/roundtable/config.env"

usage() {
  cat <<EOF
Roundtable — a council of frontier models (a Frontier Infra project)

Usage:
  roundtable "question"               Ask the council (advisory, all heads)
  roundtable ask "question" [flags]   Same, explicit
  roundtable <command> [args]

Commands:
  ask        Run the council (default when no command matches)
  auth       Add / view provider API keys (masked paste)
  models     Set the model id used by each head
  heads      Choose which heads are enabled by default
  doctor     Show per-head config + reachability
  config     Show (masked) or edit the config file ('config edit')
  mcp        Run the MCP server (e.g. 'roundtable mcp serve')
  install    Auto-wire Roundtable into detected harnesses
  version    Print the version
  update     Re-run the installer to upgrade
  help       Show this help

Engine flags (passed through to 'ask'):
  -q, --question TEXT   The question (also accepted as a positional)
  -c, --context FILE    Prepend a shared context file
      --heads CSV       Subset: claude,openai,grok,glm,minimax,gemini,codex
      --rounds N        N>=2 -> deliberation to consensus (default 1 = advisory)
      --timeout S       Per-head timeout, seconds
      --research        Allow web/tool use where heads support it
      --out FILE        Also save the transcript to FILE

Config: $RT_CONFIG_FILE
Docs:   https://roundtable.sh
EOF
}

# Value of KEY from config.env only (last match wins).
rt_cfg_value() {
  local name="$1"
  [ -f "$RT_CONFIG_FILE" ] || return 0
  grep -E "^[[:space:]]*${name}=" "$RT_CONFIG_FILE" 2>/dev/null | tail -n1 | sed -E "s/^[[:space:]]*${name}=//"
}

# Hand off to the engine, injecting default --heads when configured and the
# user didn't pass their own --heads.
exec_engine() {
  if [ ! -f "$LIBDIR/core.sh" ]; then
    echo "roundtable: engine not found ($LIBDIR/core.sh). Reinstall: curl -fsSL https://roundtable.sh/install.sh | bash" >&2
    exit 1
  fi
  local has_heads=0 a
  for a in "$@"; do [ "$a" = "--heads" ] && has_heads=1; done
  local heads_default="${ROUNDTABLE_HEADS:-}"
  [ -z "$heads_default" ] && heads_default="$(rt_cfg_value ROUNDTABLE_HEADS)"
  if [ "$has_heads" -eq 0 ] && [ -n "$heads_default" ]; then
    exec bash "$LIBDIR/core.sh" --heads "$heads_default" "$@"
  fi
  exec bash "$LIBDIR/core.sh" "$@"
}

cmd="${1:-}"
case "$cmd" in
  ""|-h|--help|help)
    usage; exit 0 ;;

  -V|--version)
    exec bash "$LIBDIR/config.sh" version ;;

  auth|models|heads|doctor|config|version|update)
    if [ ! -f "$LIBDIR/config.sh" ]; then
      echo "roundtable: $LIBDIR/config.sh is missing" >&2; exit 1
    fi
    exec bash "$LIBDIR/config.sh" "$@" ;;

  mcp)
    shift
    if [ -f "$LIBDIR/mcp.py" ]; then exec python3 "$LIBDIR/mcp.py" "$@"; fi
    echo "roundtable: MCP server not available ($LIBDIR/mcp.py missing)" >&2; exit 1 ;;

  install)
    shift
    if [ -f "$LIBDIR/install.sh" ]; then exec bash "$LIBDIR/install.sh" "$@"; fi
    echo "roundtable: installer not available ($LIBDIR/install.sh missing)" >&2; exit 1 ;;

  ask)
    shift; exec_engine "$@" ;;

  *)
    exec_engine "$@" ;;
esac
