#!/usr/bin/env bash

if [ -n "${BASH_SOURCE[0]:-}" ]; then
  _cse_toold_resolver_source="${BASH_SOURCE[0]}"
elif [ -n "${ZSH_VERSION:-}" ]; then
  _cse_toold_resolver_source="$(eval 'printf %s "${(%):-%x}"')"
else
  _cse_toold_resolver_source="$0"
fi
_cse_toold_resolver_dir="$(cd "$(dirname "$_cse_toold_resolver_source")" && pwd)"
_cse_toold_default_root="$(cd "$_cse_toold_resolver_dir/../.." && pwd)"

_cse_toold_path_prepend_once() {
  local dir="$1"
  case ":${PATH:-}:" in
    *":$dir:"*) ;;
    *) export PATH="$dir${PATH:+:$PATH}" ;;
  esac
}

_cse_first_toold_platform_bin() {
  local root="$1" expected_version="${2:-}" candidate candidate_version
  [ -d "$root/node_modules/@postman-cse" ] || return 1

  while IFS= read -r candidate; do
    [ -x "$candidate" ] || continue
    if [ -n "$expected_version" ]; then
      candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
      [ "$candidate_version" = "$expected_version" ] || continue
    fi
    printf '%s\n' "$candidate"
    return 0
  done < <(find "$root/node_modules/@postman-cse" -path '*/bin/cse-toold' -type f -print 2>/dev/null)

  return 1
}

_cse_toold_hoisted_root() {
  local root="$1"
  case "$root" in
    */node_modules/@postman-cse/*)
      (cd "$root/../../.." && pwd)
      ;;
    *)
      return 1
      ;;
  esac
}

_cse_toold_package_version() {
  local root="$1"
  [ -f "$root/package.json" ] || return 1
  sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$root/package.json" | head -n1
}

_cse_toold_binary_version() {
  local binary="$1" output word
  output="$("$binary" --version 2>/dev/null)" || return 1
  for word in $output; do
    case "$word" in
      [0-9]*.[0-9]*.[0-9]*) printf '%s\n' "$word"; return 0 ;;
    esac
  done
  return 1
}

_cse_toold_version_at_least() {
  local actual="${1%%-*}" expected="${2%%-*}"
  local actual_major actual_minor actual_patch expected_major expected_minor expected_patch
  IFS=. read -r actual_major actual_minor actual_patch <<<"$actual"
  IFS=. read -r expected_major expected_minor expected_patch <<<"$expected"
  case "$actual_major$actual_minor$actual_patch$expected_major$expected_minor$expected_patch" in
    ''|*[!0-9]*) return 1 ;;
  esac
  [ "$actual_major" -gt "$expected_major" ] && return 0
  [ "$actual_major" -lt "$expected_major" ] && return 1
  [ "$actual_minor" -gt "$expected_minor" ] && return 0
  [ "$actual_minor" -lt "$expected_minor" ] && return 1
  [ "$actual_patch" -ge "$expected_patch" ]
}

_cse_toold_root_list() {
  local root seen=":"

  for root in \
    "${CSE_TOOLD_INSTALL_ROOT:-}" \
    "$_cse_toold_default_root" \
    "${PLUGIN_ROOT:-}" \
    "${CLAUDE_PLUGIN_ROOT:-}" \
    "${DROID_PLUGIN_ROOT:-}" \
    "${CLAUDE_PLUGIN_DATA:-}"; do
    [ -n "$root" ] || continue
    case "$seen" in
      *":$root:"*) continue ;;
    esac
    seen="${seen}${root}:"
    printf '%s\n' "$root"
  done
}

_cse_resolve_toold_bin() {
  local candidate candidate_version expected_version hoisted_root package_bin required_version="" root

  if [ -n "${CSE_TOOLD_BIN:-}" ] && [ -x "${CSE_TOOLD_BIN}" ]; then
    printf '%s\n' "$CSE_TOOLD_BIN"
    return 0
  fi

  while IFS= read -r root; do
    [ -d "$root" ] || continue
    expected_version="$(_cse_toold_package_version "$root" 2>/dev/null || true)"
    if [ -n "$expected_version" ] && { [ -z "$required_version" ] || _cse_toold_version_at_least "$expected_version" "$required_version"; }; then
      required_version="$expected_version"
    fi

    candidate="$root/../../target/sea/cse-toold"
    if [ -x "$candidate" ]; then
      candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
      if [ -n "$expected_version" ] && [ "$candidate_version" = "$expected_version" ]; then
        printf '%s\n' "$candidate"
        return 0
      fi
    fi

    if package_bin="$(_cse_first_toold_platform_bin "$root" "$expected_version")"; then
      printf '%s\n' "$package_bin"
      return 0
    fi

    if hoisted_root="$(_cse_toold_hoisted_root "$root" 2>/dev/null)" && \
      package_bin="$(_cse_first_toold_platform_bin "$hoisted_root" "$expected_version")"; then
      printf '%s\n' "$package_bin"
      return 0
    fi

    candidate="$root/node_modules/.bin/cse-toold"
    if [ -f "$root/node_modules/@postman-cse/cse-toold/package.json" ] && [ -x "$candidate" ]; then
      candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
      if [ -z "$expected_version" ] || [ "$candidate_version" = "$expected_version" ]; then
        printf '%s\n' "$candidate"
        return 0
      fi
    fi

  done < <(_cse_toold_root_list)

  # Authoritative source of truth: the LaunchAgent plist points at the binary
  # self_update manages (versions/<v>/package/bin/cse-toold), which the daemon
  # actually runs and which is always current. Prefer it over the legacy stable
  # path below so a stale bin/cse-toold can never win resolution and run old
  # code. Once resolved, the hook's provision path heals bin/cse-toold from this
  # binary (current_exe), so divergence is self-correcting on the next session.
  local plist="${HOME}/Library/LaunchAgents/com.postman.cse-toold.plist"
  if [ -f "$plist" ]; then
    candidate="$(plutil -extract ProgramArguments.0 raw -o - "$plist" 2>/dev/null || true)"
    [ -n "$candidate" ] || candidate="$(plutil -extract Program raw -o - "$plist" 2>/dev/null || true)"
    if [ -n "$candidate" ] && [ -x "$candidate" ]; then
      candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
      if [ -z "$required_version" ] || _cse_toold_version_at_least "$candidate_version" "$required_version"; then
        printf '%s\n' "$candidate"
        return 0
      fi
    fi
  fi

  # Legacy stable path (B5): a fixed App Support location the installer keeps
  # byte-identical to the current binary. Cache-wipe-proof and needs no plutil,
  # so it remains the fallback when the plist is absent or points at a removed
  # binary (e.g. a wiped versions/ tree). It is intentionally BELOW the plist so
  # it can never override the authoritative, self-update-managed binary.
  candidate="${HOME}/Library/Application Support/cse-tools/bin/cse-toold"
  if [ -x "$candidate" ]; then
    candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
    if [ -z "$required_version" ] || _cse_toold_version_at_least "$candidate_version" "$required_version"; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi

  candidate="$(type -P cse-toold 2>/dev/null || true)"
  if [ -n "$candidate" ] && [ -x "$candidate" ]; then
    candidate_version="$(_cse_toold_binary_version "$candidate" 2>/dev/null || true)"
    if [ -z "$required_version" ] || _cse_toold_version_at_least "$candidate_version" "$required_version"; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi

  return 1
}

_cse_export_toold_bin() {
  local resolved
  if resolved="$(_cse_resolve_toold_bin)"; then
    export CSE_TOOLD_BIN="$resolved"
    _cse_toold_path_prepend_once "$(dirname "$resolved")"
    return 0
  fi

  unset CSE_TOOLD_BIN 2>/dev/null || true
  return 1
}

_cse_toold_install_root() {
  local root

  for root in "${CSE_TOOLD_INSTALL_ROOT:-}" "$_cse_toold_default_root" "${PLUGIN_ROOT:-}" "${CLAUDE_PLUGIN_ROOT:-}" "${DROID_PLUGIN_ROOT:-}"; do
    [ -n "$root" ] || continue
    [ -d "$root" ] || continue
    [ -f "$root/package.json" ] || continue
    printf '%s\n' "$root"
    return 0
  done

  return 1
}

_cse_toold_diagnostics() {
  local prefix="${1:-cse-toold}"
  printf '[%s] unable to resolve cse-toold (platform=%s arch=%s root=%s)\n' \
    "$prefix" "$(uname -s 2>/dev/null || echo unknown)" "$(uname -m 2>/dev/null || echo unknown)" "$_cse_toold_default_root" >&2
}
