#!/usr/bin/env bash
#ddev-generated
## Description: Verify with the trusted host escrow copy before grading
## Usage: ai-eval-verify [fixture...] [--restore]
set -euo pipefail
APPROOT=$(realpath -e "${DDEV_APPROOT:-.}")
PROJECT=${DDEV_PROJECT:-${DDEV_SITENAME:-}}
[[ "$PROJECT" =~ ^[a-zA-Z0-9_-]+$ ]] || { echo APG_ESCROW_NONE >&2; exit 1; }
ROOT=$(realpath -m "${AI_PG_ESCROW_DIR:-$HOME/.ai-proving-ground-escrow}")
[[ "$ROOT" != "$APPROOT" && "$ROOT" != "$APPROOT/"* ]] || { echo APG_ESCROW_UNSAFE >&2; exit 1; }
fixtures=()
mode=()
for arg in "$@"; do
  if [[ "$arg" == --restore ]]; then mode=(--restore); else fixtures+=("$arg"); fi
done
if [[ ${#fixtures[@]} == 0 ]]; then read -r -a fixtures <<< "${AI_PG_FIXTURES:-kb_docs canvas_home}"; fi
selection=$(printf '%s\n' "${fixtures[@]}" | jq -Rsc 'split("\n")[:-1] | sort | unique')
# Resolve from trusted metadata, never execute the bed's hash.php or ddev exec.
matches=()
shopt -s nullglob
for meta in "$ROOT/$PROJECT"/*/escrow.json; do
  if jq -e --argjson fixtures "$selection" --arg tag "${AI_PG_BASELINE_REF:-}" '.fixtures == $fixtures and ($tag == "" or .tag == $tag)' "$meta" >/dev/null; then
    matches+=("${meta%/escrow.json}")
  fi
done
[[ ${#matches[@]} == 1 ]] || { echo APG_ESCROW_NONE >&2; exit 1; }
verifier=$(realpath -e "${matches[0]}/escrow-verify.sh")
[[ "$verifier" != "$APPROOT/"* ]] || { echo APG_ESCROW_UNSAFE >&2; exit 1; }
exec bash "$verifier" "$APPROOT" "${matches[0]}" "${mode[@]}"
