#!/usr/bin/env bash
# vela-site.fly.dev/try
#
# Read-only evaluator check for the current public Vela release. It downloads
# the live release marker, flagship snapshot, one event page, the proof packet,
# and the stdlib Python verifier. It verifies advertised counts, then checks
# every proof-packet file hash.
#
# Read first:
#   curl -sSL https://vela-site.fly.dev/try | less
#
# Run:
#   curl -sSL https://vela-site.fly.dev/try | bash

set -euo pipefail

SITE_URL="${VELA_SITE_URL:-https://vela-site.fly.dev}"
HUB_URL="${VELA_HUB_URL:-https://vela-hub.fly.dev}"
VFR_ID="${VELA_DEFAULT_VFR_ID:-vfr_5076e7b3ff8e6b0f}"
WORKDIR="$(mktemp -d -t vela-try.XXXXXX)"
trap 'printf "\nfiles: %s\n" "$WORKDIR"' EXIT

require() {
  if ! command -v "$1" >/dev/null 2>&1; then
    printf 'missing required tool: %s\n' "$1" >&2
    exit 2
  fi
}

step() {
  printf 'vela try: %s\n' "$1"
}

require curl
require tar
require python3

step "fetching release marker"
curl -fsSL "$SITE_URL/release.json" -o "$WORKDIR/release.json"

step "fetching hub snapshot"
curl -fsSL "$HUB_URL/entries/$VFR_ID/snapshot" -o "$WORKDIR/snapshot.json"
curl -fsSL "$HUB_URL/entries/$VFR_ID/events?limit=1" -o "$WORKDIR/events.json"

step "fetching proof packet"
curl -fsSL "$SITE_URL/sample-packet.tar.gz" -o "$WORKDIR/sample-packet.tar.gz"
curl -fsSL "$SITE_URL/vela_verify.py" -o "$WORKDIR/vela_verify.py"
tar -xzf "$WORKDIR/sample-packet.tar.gz" -C "$WORKDIR"

PACKET_DIR="$(find "$WORKDIR" -maxdepth 2 -type d -name '*-proof-packet' | head -n1)"
if [[ -z "$PACKET_DIR" ]]; then
  printf 'no proof packet directory found after extraction\n' >&2
  exit 1
fi

step "checking live counts"
python3 - "$WORKDIR" <<'PY'
import hashlib
import json
import pathlib
import sys

workdir = pathlib.Path(sys.argv[1])
marker = json.loads((workdir / "release.json").read_text())
snapshot_path = workdir / "snapshot.json"
snapshot = json.loads(snapshot_path.read_text())
events_page = json.loads((workdir / "events.json").read_text())

expected = marker["expected"]
actual = {
    "findings": len(snapshot.get("findings", [])),
    "events": len(snapshot.get("events", [])),
    "artifacts": len(snapshot.get("artifacts", [])),
    "sources": len(snapshot.get("sources", [])),
}

for key in ("findings", "events", "artifacts", "sources"):
    if actual[key] != expected[key]:
        raise SystemExit(f"{key} mismatch: expected {expected[key]}, got {actual[key]}")

if events_page.get("log_total") != expected["events"]:
    raise SystemExit(f"event log total mismatch: expected {expected['events']}, got {events_page.get('log_total')}")

if marker.get("default_vfr_id") not in (snapshot.get("frontier_id"), snapshot.get("id")):
    raise SystemExit("snapshot frontier id does not match release marker")

print("vela try: counts ok")
print(f"frontier: {marker['default_vfr_id']}")
print(f"counts: {actual['findings']} findings, {actual['events']} events, {actual['artifacts']} artifacts, {actual['sources']} sources")
print(f"snapshot hash: {marker['snapshot_hash']}")
print(f"event-log hash: {marker['event_log_hash']}")
print(f"release marker sha256: {hashlib.sha256((workdir / 'release.json').read_bytes()).hexdigest()}")
PY

step "verifying proof packet"
python3 "$WORKDIR/vela_verify.py" "$PACKET_DIR"

cat <<EOF

vela try: ok
Workbench: $SITE_URL/workbench
Demo:      $SITE_URL/demo
Release:   $SITE_URL/release
EOF
