#!/usr/bin/env bash
# Runs the enrichment fixture through treg's routed endpoints and writes one
# receipt per call. Requires the treg CLI (https://treg.to/docs) logged in.
# Usage: scripts/run-enrichment-fixture.sh evidence/fixtures/enrichment-fixture-v1.json evidence/receipts/YYYY-MM-DD
set -euo pipefail
FIX="$1"; OUT="$2"; mkdir -p "$OUT"
mask() { # mask any email local part before storage: j***@domain
  sed -E 's/"([A-Za-z0-9._%+-])[A-Za-z0-9._%+-]*@([A-Za-z0-9.-]+\.[A-Za-z]{2,})"/"\1***@\2"/g'
}
runcall() { # $1 label, $2 endpoint, $3 json body
  local label="$1" ep="$2" body="$3" t0 t1 ms code
  t0=$(python3 -c 'import time;print(int(time.time()*1000))')
  if resp=$(treg call "$ep" --method POST --header "X-Treg-Route-Max-Cost: 0.25" --data "$body" 2>&1); then code=0; else code=$?; fi
  t1=$(python3 -c 'import time;print(int(time.time()*1000))'); ms=$((t1-t0))
  printf '%s' "$resp" | mask > "$OUT/$label.json"
  echo "{\"label\":\"$label\",\"endpoint\":\"$ep\",\"request\":$body,\"exit\":$code,\"latency_ms\":$ms,\"ts\":\"$(date -u +%FT%TZ)\"}" >> "$OUT/_calls.jsonl"
  echo "$label $ep ${ms}ms exit=$code"
}
n=$(jq '.people|length' "$FIX")
for i in $(seq 0 $((n-1))); do
  id=$(jq -r ".people[$i].id" "$FIX"); body=$(jq -c ".people[$i]|{full_name,domain}" "$FIX")
  runcall "email-find-$id" treg.people.email.find "$body"
  runcall "people-enrich-$id" treg.people.enrich "$body"
done
m=$(jq '.companies|length' "$FIX")
for i in $(seq 0 $((m-1))); do
  id=$(jq -r ".companies[$i].id" "$FIX"); body=$(jq -c ".companies[$i]|{domain}" "$FIX")
  runcall "company-enrich-$id" treg.companies.enrich "$body"
done
# verify every found email (unmasked value read from the live response is not stored; we re-read from treg output before masking)
