#!/usr/bin/env bash
# Generated by scripts/sync-shim-wrappers.sh from
# packages/shared/lib/shim-wrapper-template.sh. DO NOT EDIT individual
# shim files in packages/*/bin/wr-* directly; edit the template + run
# `npm run sync:shim-wrappers` to regenerate.
#
# Resolution (ADR-080):
#   1. If the wrapper's parent dir is semver-shaped, treat as installed-
#      cache execution and resolve to the highest-version sibling's
#      scripts/ entry below.
#   2. Otherwise (parent dir is e.g. `architect`), treat as source-
#      monorepo execution and dispatch to own scripts/. The source-repo-
#      guard `exec` is the anchor parsed by
#      packages/retrospective/scripts/check-tarball-shipped-shims.sh.
#   3. If the cache parent contains zero semver-shaped siblings, exit
#      127 with a stderr message naming the cache parent (per SQ-080-2).
#
# @adr ADR-080 (highest-version-wins shim wrapper plugin scaffold)
# @adr ADR-049 (plugin-bundled scripts resolve via bin/ on $PATH — amended)
# @problem P343 (mid-session staleness window)

set -euo pipefail

SHIM_DIR="$(cd "$(dirname "$0")" && pwd)"
OWN_VERSION_DIR="$(dirname "$SHIM_DIR")"
OWN_VERSION_NAME="$(basename "$OWN_VERSION_DIR")"
CACHE_PARENT="$(dirname "$OWN_VERSION_DIR")"

SEMVER_RE='^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$'

# Source-repo guard: own parent dir is NOT semver → dispatch to own scripts/.
if ! [[ "$OWN_VERSION_NAME" =~ $SEMVER_RE ]]; then
  exec "$SHIM_DIR/../scripts/mark-create-gate.sh" "$@"
fi

# Cache execution: pick the highest-semver sibling under CACHE_PARENT.
HIGHEST=""
while IFS= read -r dir; do
  name="$(basename "$dir")"
  [[ "$name" =~ $SEMVER_RE ]] || continue
  if [[ -z "$HIGHEST" ]] || [[ "$(printf '%s\n%s\n' "$HIGHEST" "$name" | sort -V | tail -1)" == "$name" ]]; then
    HIGHEST="$name"
  fi
done < <(find "$CACHE_PARENT" -mindepth 1 -maxdepth 1 -type d 2>/dev/null)

if [[ -z "$HIGHEST" ]]; then
  printf 'wr-shim: no cached versions in %s\n' "$CACHE_PARENT" >&2
  exit 127
fi

exec "$CACHE_PARENT/$HIGHEST/scripts/mark-create-gate.sh" "$@"
