#!/usr/bin/env bash
# Sends the fixture's company domains to Treg's routed company enrichment, once
# unpinned and once pinned to each named provider (X-Treg-Route-Prefer with the
# waterfall off, so a miss stays a miss), and writes one receipt per call:
# company-fields-<provider>-<id>.json. Requires the treg CLI (https://treg.to/docs) logged in.
# Usage: scripts/run-company-fields-fixture.sh evidence/fixtures/enrichment-fixture-v1.json evidence/receipts/YYYY-MM-DD "hunter apollo" [limit]
set -euo pipefail
FIX="$1"; OUT="$2"; PROVIDERS="$3"; LIMIT="${4:-0}"; mkdir -p "$OUT"
mask() { # mask any email local part before storage, wherever it appears (a URL too): 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 json body, remaining args: extra headers
  local label="$1" body="$2" t0 t1 ms code; shift 2
  t0=$(python3 -c 'import time;print(int(time.time()*1000))')
  if resp=$(treg call treg.companies.enrich --method POST --header "X-Treg-Route-Max-Cost: 0.5" "$@" --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"
  printf '{"label":"%s","endpoint":"treg.companies.enrich","request":%s,"exit":%s,"latency_ms":%s,"ts":"%s"}\n' \
    "$label" "$body" "$code" "$ms" "$(date -u +%FT%TZ)" | mask >> "$OUT/_calls.jsonl"
  echo "$label ${ms}ms exit=$code"
}
m=$(jq '.companies|length' "$FIX"); [ "$LIMIT" -gt 0 ] && [ "$LIMIT" -lt "$m" ] && m="$LIMIT"
for p in $PROVIDERS; do
  for i in $(seq 0 $((m-1))); do
    id=$(jq -r ".companies[$i].id" "$FIX"); body=$(jq -c ".companies[$i]|{domain}" "$FIX")
    if [ "$p" = routed ]; then
      runcall "company-fields-routed-$id" "$body"
    else
      runcall "company-fields-$p-$id" "$body" --header "X-Treg-Route-Prefer: $p" --header "X-Treg-Route-Waterfall: 0"
    fi
  done
done
