#!/usr/bin/env bash
# API port — single source of truth: node/.env PORT
# shellcheck disable=SC2034

node_env_port() {
  local root="${1:-}"
  if [[ -z "$root" ]]; then
    root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
  fi
  local env_file="$root/node/.env"
  if [[ ! -f "$env_file" ]]; then
    printf 'Error: %s not found\n' "$env_file" >&2
    return 1
  fi
  local port
  port="$(grep -E '^PORT=' "$env_file" | tail -1 | cut -d= -f2- | tr -d ' "'\''')"
  if [[ -z "$port" || ! "$port" =~ ^[0-9]+$ ]]; then
    printf 'Error: PORT is not set (or invalid) in %s\n' "$env_file" >&2
    return 1
  fi
  echo "$port"
}
