#!/usr/bin/env bash
# floom — deploy AI apps to Floom from any shell or agent.
#
# Subcommands:
#   init      scaffold floom.yaml in the current directory
#   deploy    validate + publish the current app
#   account   manage workspace secrets and agent tokens
#   status    list your apps and recent runs
#   login     open the token page and print login instructions
#   setup     open the token page and print login instructions
#   auth      save an Agent token to ~/.floom/config.json
#   --help    show this help
#   --version print version

set -euo pipefail

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}" 2>/dev/null || readlink "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
BIN_DIR="$SCRIPT_DIR"
ROOT_DIR="$(cd "$BIN_DIR/.." && pwd)"
LIB_DIR="$ROOT_DIR/lib"

print_help() {
  cat <<'EOF'
floom — run and deploy AI apps from any shell or agent.

usage:
  floom <command> [options]

commands:
  login               open the token page and print login instructions
  setup               open the token page and print login instructions
  auth <agent-token>  save an Agent token to ~/.floom/config.json
  account             manage workspace secrets and agent tokens
  apps list           list your workspace apps
  apps update         update, share, or delete workspace apps
  run <slug> [json]   run a Floom app by slug and wait for the result
  init                scaffold a floom.yaml in the current directory
  deploy              validate + publish the current app (use --dry-run to preview)
  status              list your apps and recent runs

options:
  --help, -h        show this help
  --version, -v     print version

docs:     https://floom.dev/docs
examples: https://github.com/floomhq/floom/tree/main/examples
agent tokens: https://floom.dev/me/agent-keys
EOF
}

print_version() {
  if [[ -f "$ROOT_DIR/VERSION" ]]; then
    cat "$ROOT_DIR/VERSION"
  else
    echo "unknown"
  fi
}

CMD="${1:-}"
if [[ $# -gt 0 ]]; then shift; fi

case "$CMD" in
  ""|-h|--help|help)
    print_help
    [[ "$CMD" == "" ]] && exit 1
    exit 0 ;;
  -v|--version|version)
    print_version
    exit 0 ;;
  init)
    exec bash "$LIB_DIR/floom-init.sh" "$@" ;;
  deploy)
    exec bash "$LIB_DIR/floom-deploy.sh" "$@" ;;
  status)
    exec bash "$LIB_DIR/floom-status.sh" "$@" ;;
  login|setup)
    exec bash "$LIB_DIR/floom-auth.sh" login "$@" ;;
  auth)
    exec bash "$LIB_DIR/floom-auth.sh" "$@" ;;
  account)
    exec bash "$LIB_DIR/floom-account.sh" "$@" ;;
  apps)
    exec bash "$LIB_DIR/floom-apps.sh" "$@" ;;
  run)
    exec bash "$LIB_DIR/floom-run.sh" "$@" ;;
  validate)
    exec bash "$LIB_DIR/floom-validate.sh" "$@" ;;
  api)
    exec bash "$LIB_DIR/floom-api.sh" "$@" ;;
  *)
    echo "floom: unknown command '$CMD'" >&2
    echo "run 'floom --help' for usage." >&2
    exit 1 ;;
esac
