#!/bin/bash
# fleet — QA Fleet CLI unified dispatcher
set -euo pipefail

# Resolve fleet root (follow symlinks)
_src="${BASH_SOURCE[0]}"
while [ -L "$_src" ]; do _src="$(readlink "$_src")"; done
FLEET_ROOT="$(cd "$(dirname "$_src")" && pwd)"
export FLEET_ROOT

# Source shared library
source "$FLEET_ROOT/cli/common.sh"

cmd="${1:-help}"
shift || true

case "$cmd" in
  --write-examples)
    write_examples "$@"
    ;;
  init)            exec "$FLEET_ROOT/cli/cmd-init.sh" "$@" ;;
  add)             exec "$FLEET_ROOT/cli/cmd-add.sh" "$@" ;;
  ls)              exec "$FLEET_ROOT/cli/cmd-ls.sh" "$@" ;;
  rm)              exec "$FLEET_ROOT/cli/cmd-rm.sh" "$@" ;;
  restart)         exec "$FLEET_ROOT/cli/cmd-restart.sh" "$@" ;;
  stop)            exec "$FLEET_ROOT/cli/cmd-stop.sh" "$@" ;;
  start)           exec "$FLEET_ROOT/cli/cmd-start.sh" "$@" ;;
  push)            exec "$FLEET_ROOT/cli/cmd-push.sh" "$@" ;;
  sync)            exec "$FLEET_ROOT/cli/cmd-sync.sh" "$@" ;;
  migrate-names)   exec "$FLEET_ROOT/cli/cmd-migrate-names.sh" "$@" ;;
  install-claude)
    command -v node >/dev/null 2>&1 || { echo "[fleet] ERROR: node is required for 'install-claude'" >&2; exit 1; }
    exec node "$FLEET_ROOT/bin/fleet.js" install-claude "$@"
    ;;
  help|--help|-h)
    # fleet help <cmd> → delegate to that command's --help (single source of truth)
    if [ -n "${1:-}" ]; then
      subcmd="$1"
      shift
      case "$subcmd" in
        init)           exec "$FLEET_ROOT/cli/cmd-init.sh" --help ;;
        add)            exec "$FLEET_ROOT/cli/cmd-add.sh" --help ;;
        ls)             exec "$FLEET_ROOT/cli/cmd-ls.sh" --help ;;
        rm)             exec "$FLEET_ROOT/cli/cmd-rm.sh" --help ;;
        restart)        exec "$FLEET_ROOT/cli/cmd-restart.sh" --help ;;
        stop)           exec "$FLEET_ROOT/cli/cmd-stop.sh" --help ;;
        start)          exec "$FLEET_ROOT/cli/cmd-start.sh" --help ;;
        push)           exec "$FLEET_ROOT/cli/cmd-push.sh" --help ;;
        sync)           exec "$FLEET_ROOT/cli/cmd-sync.sh" --help ;;
        migrate-names)  exec "$FLEET_ROOT/cli/cmd-migrate-names.sh" --help ;;
        install-claude)
          command -v node >/dev/null 2>&1 || { echo "[fleet] ERROR: node is required for 'install-claude'" >&2; exit 1; }
          exec node "$FLEET_ROOT/bin/fleet.js" install-claude --help
          ;;
        *)
          error "No help available for unknown command: $subcmd\nRun 'fleet help' for the full command list."
          ;;
      esac
    fi
    show_help
    ;;
  *)
    error "Unknown command: $cmd\nRun 'fleet help' for usage."
    ;;
esac
