#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

usage() {
  local bold=$'\033[1m' dim=$'\033[2m' reset=$'\033[0m' cyan=$'\033[36m'

  cat <<EOF
${bold}fireclaw${reset} — Firecracker microVM control plane

${bold}USAGE${reset}
  fireclaw <command> [args...]

${bold}COMMANDS${reset}
  ${cyan}doctor${reset}                       Check host prerequisites
  ${cyan}setup${reset} <flags...>             Create and provision a new VM instance
  ${cyan}provision${reset} <id> [flags...]     Update saved config and re-run guest provisioning
  ${cyan}list${reset}                         List all instances
  ${cyan}status${reset} [id]                  Show instance status (all or one)
  ${cyan}start${reset} <id>                   Start an instance
  ${cyan}stop${reset} <id>                    Stop an instance (stays stopped across host reboots)
  ${cyan}restart${reset} <id>                 Restart an instance
  ${cyan}logs${reset} <id> [guest|host]       Stream logs
  ${cyan}shell${reset} <id> [command...]      SSH into VM or run a command
  ${cyan}token${reset} <id>                   Print gateway token
  ${cyan}destroy${reset} <id> [--force]       Destroy an instance

${bold}EXAMPLES${reset}
  ${dim}\$${reset} sudo fireclaw doctor
  ${dim}\$${reset} sudo fireclaw setup --instance my-bot --openai-api-key <key>
  ${dim}\$${reset} sudo fireclaw setup --instance my-bot --telegram-token <tok> --telegram-users <uid> --openai-api-key <key>
  ${dim}\$${reset} sudo fireclaw provision my-bot --model openai/gpt-5.5
  ${dim}\$${reset} sudo fireclaw list
  ${dim}\$${reset} sudo fireclaw status my-bot
  ${dim}\$${reset} sudo fireclaw shell my-bot
  ${dim}\$${reset} sudo fireclaw logs my-bot guest
EOF
}

[[ $# -ge 1 ]] || {
  usage
  exit 1
}

cmd="$1"
shift || true

case "$cmd" in
  setup|create|provision)
    if [[ "$cmd" == "provision" ]]; then
      VM_PROVISION_CMD_NAME="fireclaw provision" exec "$SCRIPT_DIR/vm-provision" "$@"
    fi
    VM_SETUP_CMD_NAME="fireclaw setup" exec "$SCRIPT_DIR/vm-setup" "$@"
    ;;
  doctor|list|status|start|stop|restart|logs|shell|token|destroy)
    if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || "${1:-}" == "help" ]]; then
      VM_CTL_CMD_NAME="fireclaw" exec "$SCRIPT_DIR/vm-ctl" --help
    fi
    VM_CTL_CMD_NAME="fireclaw" exec "$SCRIPT_DIR/vm-ctl" "$cmd" "$@"
    ;;
  ctl|vm-ctl)
    VM_CTL_CMD_NAME="fireclaw ctl" exec "$SCRIPT_DIR/vm-ctl" "$@"
    ;;
  vm-setup)
    VM_SETUP_CMD_NAME="fireclaw vm-setup" exec "$SCRIPT_DIR/vm-setup" "$@"
    ;;
  help|-h|--help)
    usage
    ;;
  *)
    echo "Error: unknown command '$cmd'" >&2
    usage
    exit 1
    ;;
esac
