#!/usr/bin/env bash
# List compose services for this workspace.
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

usage() {
  cat <<EOF
Usage: ${RUN_CMD:-run-stack} services [--raw]

List Docker Compose services configured for this workspace.

  --raw        One service name per line (same as completion)
  -h, --help   Show this help
EOF
}

service_status() {
  local name="$1"
  docker ps -a \
    --filter "label=com.docker.compose.project=${PROJECT_NAME}" \
    --filter "label=com.docker.compose.service=${name}" \
    --format '{{.Status}}' 2>/dev/null | head -1
}

print_services_table() {
  local names name status rows
  names="$(remember_and_list_services)"
  if [ -z "${names}" ]; then
    echo "No services found for this workspace." >&2
    echo "Run ${RUN_CMD:-run-stack} up once, or check .run/.env." >&2
    return 1
  fi

  rows="$(printf '%s\t%s' "SERVICE" "STATUS")"
  while IFS= read -r name; do
    [ -n "${name}" ] || continue
    status="—"
    if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
      status="$(service_status "${name}")"
      [ -n "${status}" ] || status="not created"
    fi
    rows="${rows}$(printf '\n%s\t%s' "${name}" "${status}")"
  done <<< "${names}"

  _print_tsv_table "Services" "${rows}"
}

case "${1:-}" in
  "" )
    ensure_env
    print_services_table
    ;;
  --raw)
    ensure_env
    remember_and_list_services
    ;;
  -h|--help|help)
    usage
    ;;
  *)
    echo "unknown option: $1" >&2
    usage >&2
    exit 1
    ;;
esac
