#!/usr/bin/env bash
#
# P0 release gate for the focused anti-amyloid flagship frontier.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

FRONTIER="projects/anti-amyloid-translation"
VFR_ID="vfr_5076e7b3ff8e6b0f"
VELA="./target/release/vela"

if [[ ! -x "$VELA" ]]; then
  cargo build --release --bin vela >/dev/null
fi

"$VELA" check "$FRONTIER" --strict --json >/tmp/vela-anti-amyloid-check.json
jq -e '.ok == true' /tmp/vela-anti-amyloid-check.json >/dev/null

"$VELA" decision-brief "$FRONTIER" --json >/tmp/vela-anti-amyloid-decision.json
jq -e '.ok == true and (.projection.questions | length == 6) and (.issues | length == 0)' /tmp/vela-anti-amyloid-decision.json >/dev/null

"$VELA" trial-summary "$FRONTIER" --json >/tmp/vela-anti-amyloid-trials.json
jq -e '.ok == true and (.projection.rows | length >= 7) and (.issues | length == 0)' /tmp/vela-anti-amyloid-trials.json >/dev/null

"$VELA" source-verification "$FRONTIER" --json >/tmp/vela-anti-amyloid-source-verification.json
jq -e '.ok == true and (.projection.sources | length >= 6) and (.issues | length == 0)' /tmp/vela-anti-amyloid-source-verification.json >/dev/null

rm -rf /tmp/vela-anti-amyloid-proof-p0
"$VELA" proof "$FRONTIER" --out /tmp/vela-anti-amyloid-proof-p0 --json >/tmp/vela-anti-amyloid-proof.json
test -f /tmp/vela-anti-amyloid-proof-p0/proof-trace.json
test -f /tmp/vela-anti-amyloid-proof-p0/artifacts/artifacts.json
jq -e '.status == "ok" and .replay_status == "ok"' /tmp/vela-anti-amyloid-proof-p0/proof-trace.json >/dev/null

./scripts/check-artifact-integrity.py "$FRONTIER" --json >/tmp/vela-anti-amyloid-artifacts.json
jq -e '.ok == true and .artifact_count >= 31 and .issue_count == 0' /tmp/vela-anti-amyloid-artifacts.json >/dev/null

./scripts/check-source-freshness.py "$FRONTIER" --max-age-days 45 --json >/tmp/vela-anti-amyloid-sources.json
jq -e '.ok == true and .source_count >= 6 and .issue_count == 0' /tmp/vela-anti-amyloid-sources.json >/dev/null

./scripts/audit-live-frontiers.sh --frontier "$VFR_ID" --json >/tmp/vela-anti-amyloid-live.json
jq -e '.ok == true and .frontier_count == 1 and .frontiers[0].live == true and .frontiers[0].snapshot_verified == true and .frontiers[0].events_verified == true' /tmp/vela-anti-amyloid-live.json >/dev/null

printf "anti-amyloid release: ok\n"
