#!/usr/bin/env bash
# One-shot: wait for Safe Site EXO app-only access to propagate, then pull the recall proof.
set -uo pipefail
cd "$(git rev-parse --show-toplevel)"
SK=~/.claude/skills/remediation-tool/scripts; [ -d "$SK" ] || SK=.claude/skills/remediation-tool/scripts
export VAULT_ROOT_ENV="$(jq -r '.vault_path // "D:/vault"' .claude/identity.json)"
TID=71b4e637-c802-4137-a812-ae50dbc839e3
EXURL="https://outlook.office365.com/adminapi/beta/$TID/InvokeCommand"
OUT="/c/Users/guru/Downloads/safesite-recall-proof.json"
inv(){ local tok="$1" payload="$2"; curl -s -m 90 -X POST "$EXURL" -H "Authorization: Bearer $tok" -H "Content-Type: application/json" -d "$payload" | tr -d '\000'; }

echo "[poller] waiting for EXO app-only propagation (up to ~75 min)..."
for i in $(seq 1 15); do
  EOP=$(bash "$SK/get-token.sh" safesitellc.com exchange-op 2>/dev/null | tr -d '[:space:]')
  RC=$(curl -s -o /dev/null -m 60 -w '%{http_code}' -X POST "$EXURL" -H "Authorization: Bearer $EOP" -H "Content-Type: application/json" -d '{"CmdletInput":{"CmdletName":"Get-OrganizationConfig","Parameters":{}}}')
  echo "[poller] attempt $i: Get-OrganizationConfig HTTP $RC"
  if [ "$RC" = "200" ]; then
    echo "[poller] EXO READY — pulling recall proof..."
    {
      echo "{"
      echo "\"pulled_at\":\"$(date -u +%FT%TZ)\","
      echo "\"audit_freetext_SSUS\":"
      inv "$EOP" '{"CmdletInput":{"CmdletName":"Search-UnifiedAuditLog","Parameters":{"StartDate":"2026-06-08","EndDate":"2026-06-09","FreeText":"SSUS 06122026","ResultSize":500}}}'
      echo ","
      echo "\"audit_deletes_recipients\":"
      inv "$EOP" '{"CmdletInput":{"CmdletName":"Search-UnifiedAuditLog","Parameters":{"StartDate":"2026-06-08","EndDate":"2026-06-09","Operations":["HardDelete","SoftDelete","MoveToDeletedItems"],"UserIds":["beeanna@safesitellc.com","david@safesitellc.com","jeremiahw@safesitellc.com","jon@safesitellc.com","justinb@safesitellc.com","lennyg@safesitellc.com","suzannep@safesitellc.com","thomasc@safesitellc.com","travisf@safesitellc.com"],"ResultSize":500}}}'
      echo ","
      echo "\"message_trace_mparis\":"
      inv "$EOP" '{"CmdletInput":{"CmdletName":"Get-MessageTraceV2","Parameters":{"SenderAddress":"m.paris@nexsitepartners.com","StartDate":"2026-06-08T00:00:00","EndDate":"2026-06-09T00:00:00"}}}'
      echo "}"
    } > "$OUT" 2>&1
    echo "[poller] DONE -> $OUT"
    echo "[poller] quick tally:"
    echo "  audit FreeText 'SSUS 06122026' rows: $(jq '.audit_freetext_SSUS.value|length' "$OUT" 2>/dev/null || echo '?')"
    echo "  audit delete/purge rows (recipients): $(jq '.audit_deletes_recipients.value|length' "$OUT" 2>/dev/null || echo '?')"
    exit 0
  fi
  sleep 300
done
echo "[poller] EXO still not ready after 75 min — coord todo 7ddc8ebd remains for a later session."
exit 0
