#!/usr/bin/env bash

# Reads only explicit request-membership manifests for commits in a deployed range. The caller owns
# the output array; commit messages, branches, timestamps, and request prose are never inspected.
delivery_manifest_collect() {
  local git_root=$1 manifest_dir=$2 previous=$3 target=$4 output_name=$5
  local commit manifest request_id
  local -a commits=()
  local -A seen=()
  local -n output=$output_name
  output=()
  [[ "$target" =~ ^[0-9a-f]{40}$ ]] || return 1
  if [[ "$previous" =~ ^[0-9a-f]{40}$ ]] && git -C "$git_root" merge-base --is-ancestor "$previous" "$target" 2>/dev/null; then
    mapfile -t commits < <(git -C "$git_root" rev-list --reverse "$previous..$target") || return 1
  else
    commits=("$target")
  fi
  for commit in "${commits[@]}"; do
    manifest="$manifest_dir/$commit.requests"
    [[ -r "$manifest" ]] || continue
    while IFS= read -r request_id; do
      [[ "$request_id" =~ ^[A-Za-z0-9._:-]{1,240}$ ]] || return 1
      [[ -z "${seen[$request_id]:-}" ]] || continue
      seen[$request_id]=1
      output+=("$request_id")
    done < "$manifest"
  done
}
