#!/usr/bin/env bash
# breathe-port.sh — single source for service PORT resolution (config-as-code).
#
# The shipped source of truth is the daemon package contract:
# config/shipping/package.ship.json or package.json → cogitodBundle.daemon.port.
#
# resolve_port <service>   — port for a service.
#   Order (first match wins):
#     1. <SERVICE>_PORT env var               (caller override, e.g. KERNEL_PORT)
#     2. ~/.cogito/breathe/<service>.port            (runtime truth, if the service writes one)
#     3. daemon package contract              (cogitod only)
#     4. empty (caller decides) — resolve_port never invents a number
#
# breathe_port()  — cogitod specialization (BREATHE_PORT env, ~/.cogito/breathe/port,
#                   package contract, then safety fallback 24567). Back-compat:
#                   sourcing this file eager-sets $BREATHE_PORT.
#
# Works with set -euo pipefail (never exits on its own).

_BREATHE_PORT_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

_package_contract_path() {
  local dir="$_BREATHE_PORT_LIB_DIR"
  while [ "$dir" != "/" ]; do
    if [ -f "$dir/config/shipping/package.ship.json" ]; then echo "$dir/config/shipping/package.ship.json"; return 0; fi
    if [ -f "$dir/package.json" ]; then echo "$dir/package.json"; return 0; fi
    dir="$(dirname "$dir")"
  done
}

_port_from_contract() {
  local svc="$1"
  [ "$svc" = "cogitod" ] || return 0
  local contract; contract="$(_package_contract_path)"
  [ -n "$contract" ] || return 0
  node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); const port=p.cogitodBundle?.daemon?.port; if (Number.isInteger(port)) process.stdout.write(String(port));" "$contract" 2>/dev/null || true
}

# resolve_port <service> [runtime-file]
resolve_port() {
  local svc="$1"
  local rtfile="${2:-$HOME/.cogito/breathe/${svc}.port}"
  # 1. <SERVICE>_PORT env override
  # (bash 3.2 on stock macOS lacks ${svc^^} uppercase expansion — use tr so shipped
  # hooks that source this lib don't die at parse time.)
  local envvar; envvar="$(printf '%s' "$svc" | tr '[:lower:]' '[:upper:]')_PORT"
  if [ -n "${!envvar:-}" ]; then echo "${!envvar}"; return 0; fi
  # 2. runtime port file
  if [ -f "$rtfile" ]; then
    local rt; rt=$(tr -d '[:space:]' < "$rtfile" 2>/dev/null || true)
    [ -n "$rt" ] && { echo "$rt"; return 0; }
  fi
  # 3. package contract
  _port_from_contract "$svc"
}

# cogitod specialization — BREATHE_PORT env + ~/.cogito/breathe/port runtime file +
# package contract + safety fallback 24567.
breathe_port() {
  if [ -n "${BREATHE_PORT:-}" ]; then echo "$BREATHE_PORT"; return 0; fi
  local p; p=$(resolve_port cogitod "$HOME/.cogito/breathe/port")
  echo "${p:-24567}"
}

# Eager back-compat: scripts that source this can use $BREATHE_PORT directly.
BREATHE_PORT="${BREATHE_PORT:-$(breathe_port)}"
