#!/usr/bin/env bash
# JIL Sovereign · MCO Payment Integrity · CLI Walkthrough (exhaustive)
# Self-contained Bash port of /products/mco-payment-integrity-demo.
# Walks the showcase engagement (eng-mco-dmepos-2024-showcase) through six
# stages in ~45 seconds with the same numbers as the web demo plus every
# intermediate operation (table-by-table ingest · per-check T1 fire ·
# cluster-graph construction · per-vendor API responses · Merkle leaves ·
# per-validator signatures).
#
# Usage:
#   ./mco-walkthrough.sh                 # full animated walkthrough (~45s)
#   ./mco-walkthrough.sh --fast          # skip per-line animation
#   ./mco-walkthrough.sh --no-color      # plain ASCII for log piping
#   ./mco-walkthrough.sh --json          # machine-readable output, no animation
#
# No external dependencies. Tested on bash 4.4+, GNU coreutils.

set -u

# ---- flags ------------------------------------------------------------------
FAST=0; NOCOLOR=0; JSON=0
for a in "$@"; do
  case "$a" in
    --fast)      FAST=1 ;;
    --no-color)  NOCOLOR=1 ;;
    --json)      JSON=1; NOCOLOR=1 ;;
    -h|--help)
      sed -n '2,20p' "$0" | sed 's/^# //; s/^#//'
      exit 0 ;;
    *)
      echo "Unknown flag: $a" >&2; exit 2 ;;
  esac
done

# ---- colors -----------------------------------------------------------------
if [[ $NOCOLOR -eq 1 || ! -t 1 ]]; then
  BOLD=""; DIM=""; RESET=""; RED=""; GREEN=""; GOLD=""; NAVY=""; CYAN=""; INV=""
else
  BOLD=$'\033[1m'; DIM=$'\033[2m'; RESET=$'\033[0m'
  RED=$'\033[38;5;131m'; GREEN=$'\033[38;5;71m'; GOLD=$'\033[38;5;179m'
  NAVY=$'\033[38;5;67m'; CYAN=$'\033[38;5;109m'; INV=$'\033[7m'
fi

# ---- helpers ---------------------------------------------------------------
SPINNER=( "⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏" )
if [[ $NOCOLOR -eq 1 ]]; then SPINNER=( "|" "/" "-" "\\" "|" "/" "-" "\\" ); fi

# Per-line reveal delay (seconds). 0 in --fast or --json.
PACE=0.12
if [[ $FAST -eq 1 || $JSON -eq 1 ]]; then PACE=0; fi
delay() {
  if [[ $PACE = "0" ]]; then return; fi
  sleep "$PACE"
}

pause() {
  if [[ $JSON -eq 1 ]]; then return; fi
  if [[ $FAST -eq 1 ]]; then return; fi
  sleep "$1"
}

spin_for() {
  local dur=$1; local label=$2
  if [[ $JSON -eq 1 || $FAST -eq 1 ]]; then return; fi
  local frames=$(( ${dur%.*} * 10 + 5 ))
  for ((i=0; i<frames; i++)); do
    local frame=${SPINNER[$(( i % ${#SPINNER[@]} ))]}
    printf "\r  %s%s%s %s    " "$GOLD" "$frame" "$RESET" "$label"
    sleep 0.08
  done
  printf "\r%-110s\r" " "
}

stage_start() {
  local n=$1; local title=$2
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "\n${BOLD}${NAVY}[%s]${RESET} ${BOLD}%s${RESET}\n" "$n" "$title"
}

stage_done() {
  local n=$1; local label=$2; local secs=$3
  if [[ $JSON -eq 1 ]]; then
    printf '{"stage":%d,"label":"%s","wall_seconds":%s,"status":"complete"}\n' "$n" "$label" "$secs"
    return
  fi
  printf "  ${GREEN}✓${RESET} ${DIM}%s · %ss wall${RESET}\n" "$label" "$secs"
}

# Output helpers (suppressed in JSON mode).
say() {
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "     ${DIM}│${RESET} %s\n" "$1"
  delay
}
ok() {
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "     ${DIM}│${RESET} ${GREEN}✓${RESET} %s\n" "$1"
  delay
}
flag() {
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "     ${DIM}│${RESET} ${RED}✗${RESET} %s\n" "$1"
  delay
}
note() {
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "     ${DIM}│${RESET} ${DIM}%s${RESET}\n" "$1"
  delay
}
sep() {
  if [[ $JSON -eq 1 ]]; then return; fi
  printf "     ${DIM}│${RESET}\n"
}

# ---- header ----------------------------------------------------------------
if [[ $JSON -eq 0 ]]; then
  clear 2>/dev/null || true
  printf "\n${BOLD}${NAVY}╔══════════════════════════════════════════════════════════════════════════╗${RESET}\n"
  printf   "${BOLD}${NAVY}║${RESET}  ${BOLD}JIL Sovereign${RESET} · MCO Payment Integrity · ${GOLD}Live Walkthrough${RESET}            ${BOLD}${NAVY}║${RESET}\n"
  printf   "${BOLD}${NAVY}║${RESET}  Engagement: ${CYAN}eng-mco-dmepos-2024-showcase${RESET}                              ${BOLD}${NAVY}║${RESET}\n"
  printf   "${BOLD}${NAVY}║${RESET}  ${DIM}six stages · exhaustive trace · numbers tie to the live AVA workspace${RESET} ${BOLD}${NAVY}║${RESET}\n"
  printf   "${BOLD}${NAVY}╚══════════════════════════════════════════════════════════════════════════╝${RESET}\n"
fi
# JSON mode emits NDJSON: one stage_done object per stage, then a summary.

START=$(date +%s.%N)

# ============================================================================
# STAGE 01 · DATA INGESTION
# ============================================================================
stage_start "01" "Data ingestion · CMS public data + LEIE + NPPES + SAM.gov"
spin_for 0.4 "opening keypair-auth session to JIL_DATA on KFSNCLK-SI27750"
note "Snowflake connection: warehouse=COMPUTE_WH_S · role=JIL_READER · 142ms handshake"
note "Read isolation: customer perimeter sealed · no customer PHI requested · only public sources"
sep
say "Pulling reference tables from JIL_DATA.CMS_PUBLIC.* (15-year lookback):"
ok "${CYAN}NPPES_PROVIDERS${RESET}              ${BOLD}  9,401,238${RESET} rows · sha256:8a13f...c93e2 · freshness: 18h"
ok "${CYAN}OIG_LEIE_EXCLUSIONS${RESET}          ${BOLD}     67,432${RESET} rows · sha256:b9c4d...3e9f1 · freshness: 11d"
ok "${CYAN}MEDICARE_PARTB_CLAIMS_FY22${RESET}   ${BOLD} 47,283,914${RESET} rows · sha256:2e5a1...8d4f7 · freshness: 89d"
ok "${CYAN}MEDICARE_PARTB_CLAIMS_FY23${RESET}   ${BOLD} 49,107,602${RESET} rows · sha256:c47b3...19a6e · freshness: 89d"
ok "${CYAN}MEDICARE_PARTB_CLAIMS_FY24${RESET}   ${BOLD} 49,435,794${RESET} rows · sha256:f81d9...7c25a · freshness: 12d"
ok "${CYAN}CMS_DMEPOS_FEE_SCHEDULE${RESET}      ${BOLD}     38,901${RESET} rows · sha256:1d2c8...e4f93 · freshness: 7d"
ok "${CYAN}CMS_PROVIDER_OF_SERVICES${RESET}     ${BOLD}     44,217${RESET} rows · sha256:5fe2c...0b318 · freshness: 30d"
ok "${CYAN}CMS_PECOS_OWNERSHIP${RESET}          ${BOLD}    127,403${RESET} rows · sha256:7a90d...62e4f · freshness: 45d"
ok "${CYAN}USPS_CMRA_PREMISE_REGISTRY${RESET}   ${BOLD}    241,604${RESET} rows · sha256:3b1f0...d75e2 · freshness: 32d"
ok "${CYAN}SAM_GOV_EXCLUSIONS_V4${RESET}        ${BOLD}    167,456${RESET} rows · sha256:e029a...41bc7 · freshness: 4h"
ok "${CYAN}SSA_DEATH_MASTER_FILE${RESET}        ${BOLD} 90,612,308${RESET} rows · sha256:c318f...d29b4 · freshness: 24h"
ok "${CYAN}DOJ_QUI_TAM_FILED_ACTIONS${RESET}    ${BOLD}     11,807${RESET} rows · sha256:9e2d3...58fc1 · freshness: 9d"
sep
say "Total bytes scanned: ${BOLD}1.42 TB${RESET} compressed · ${BOLD}9.7 TB${RESET} uncompressed"
say "Data residency: ${BOLD}us-east-2${RESET} (Snowflake) · customer rows materialized customer-side: ${BOLD}0${RESET}"
say "Encryption: TLS 1.3 in flight · AES-256 at rest · keypair JWT auth (no password)"
stage_done 1 "Data ingestion" "0.8"
pause 0.4

# ============================================================================
# STAGE 02 · TIER 1 DETECTION
# ============================================================================
stage_start "02" "Tier 1 detection · 175 deterministic checks fire in parallel"
note "All checks deterministic + audit-traceable + statutorily-cited."
note "T1 layer is screening signal only · zero findings reach the report without T2 substantiation."
sep
say "Compute pool: ${BOLD}SPCS-COMPUTE-XL${RESET} · 8 workers · checks parallelized by entity_id"
say "Verdict-engine version: ${BOLD}ava-2026.05.28-stable${RESET}"
sep
say "Firing checks (showing top hits)..."
ok "${BOLD}DME-001${RESET}    K0823 power-wheelchair utilization > 4.0x peer median        ${RED}138${RESET} hits"
note  "          authority: 31 USC 3729 (FCA) · 42 CFR 414.230 (DMEPOS coverage)"
ok "${BOLD}DME-007${RESET}    K0858 motorized scooter · prior-auth gap                       ${RED} 47${RESET} hits"
note  "          authority: 42 CFR 414.408 (DMEPOS prior auth)"
ok "${BOLD}LEIE-001${RESET}   Active billing 90+ days post-OIG exclusion                     ${RED} 22${RESET} hits"
note  "          authority: 42 USC 1320a-7 (statutory exclusion · binary)"
ok "${BOLD}LEIE-004${RESET}   Reinstatement gap > rule-defined window                        ${RED}  9${RESET} hits"
note  "          authority: 42 CFR 1001.3001 (reinstatement)"
ok "${BOLD}PREM-001${RESET}   CMRA / virtual office address match (USPS registry)            ${RED} 31${RESET} hits"
note  "          authority: 42 CFR 424.516 (enrollment standards · brick-and-mortar)"
ok "${BOLD}PREM-003${RESET}   POS file address mismatch vs NPPES practice location           ${RED} 18${RESET} hits"
note  "          authority: 42 CFR 424.516"
ok "${BOLD}POS-001${RESET}    PECOS-deactivated NPI still billing                            ${RED} 12${RESET} hits"
note  "          authority: 42 CFR 424.520 (effective date) · 42 USC 1320a-7"
ok "${BOLD}OWN-001${RESET}    Common-owner ring across 3+ DMEPOS suppliers                   ${RED}  4${RESET} hits"
note  "          authority: 42 CFR 424.516(f) (managing employees + ownership disclosure)"
ok "${BOLD}REC-001${RESET}    Recidivism: flagged in 3+ consecutive program years            ${RED} 18${RESET} hits"
note  "          authority: 31 USC 3729 (FCA · pattern element)"
ok "${BOLD}REC-002${RESET}    Same-NPI multi-fiscal-year outlier · DRG / DMEPOS              ${RED}  9${RESET} hits"
flag "${BOLD}AKS-001${RESET}    Kickback referral concentration > 0.85                         ${DIM}  0${RESET} hits (cluster not present this engagement)"
flag "${BOLD}SSA-DMF-001${RESET} Worker SSN matches Death Master File                           ${DIM}  0${RESET} hits"
flag "${BOLD}DRG-001${RESET}    Inpatient CC/MCC outlier vs peer hospital                       ${DIM}  0${RESET} hits"
sep
say "Checks executed: ${BOLD}175${RESET} · checks producing findings: ${BOLD}10${RESET}"
say "Total findings generated: ${BOLD}1,847${RESET} · unique entities flagged: ${BOLD}209${RESET}"
say "Wall time on Snowflake: ${BOLD}3.18s${RESET} · compute credits consumed: ${BOLD}0.42${RESET}"
stage_done 2 "Tier 1 detection" "3.2"
pause 0.4

# ============================================================================
# STAGE 03 · AVA CLUSTERING
# ============================================================================
stage_start "03" "AVA clustering · 1,847 findings → entity graph → 4 case clusters"
spin_for 0.4 "constructing entity-relationship graph"
say "${BOLD}AVA-Clustering · ava-cluster-engine v2026.05.28${RESET}"
note "Runs as Snowpark Container Service inside the customer's Snowflake account."
note "Customer rows materialized outside customer perimeter: ${BOLD}0${RESET}."
sep
say "${BOLD}Algorithm stack${RESET} (every step versioned, deterministic, replayable):"
say "  ├─ Graph construction:  JIL/graphlib v2.1.4 · deterministic adjacency from SQL joins"
say "  ├─ Edge weighting:      rule-based + z-score outlier · ${BOLD}no ML model${RESET}"
say "  ├─ Community detection: NetworkX 3.2 · Louvain modularity · ${BOLD}seed=42${RESET} (reproducible)"
say "  ├─ Resolution param:    γ=1.0 · baked into engagement isolation profile · audit-sealed"
say "  └─ Cluster floor:       deterministic table · ≥ 8 entities AND ≥ \$5M exposure"
sep
say "${BOLD}What clustering IS${RESET}: grouping already-deterministic T1 findings by entity + archetype."
say "${BOLD}What clustering IS NOT${RESET}: invented findings · false-flag raising · verdict generation."
say "${BOLD}Reproducibility${RESET}: same inputs + same seed = same clusters · byte-identical · forever."
sep
say "Graph nodes:      ${BOLD}209${RESET} unique flagged entities (NPI ∪ EIN ∪ premise-address-hash)"
say "Graph edges:      ${BOLD}3,401${RESET} relationships"
note "          edge types: shared_address(622) · shared_owner(184) · co-billing(831) · sequential-billing(241) · premise-coincidence(1,523)"
say "Louvain pass:     3 iterations · Q=0.42 → Q=0.81 → Q=0.83 (converged)"
say "Partitions selected: ${BOLD}4${RESET} (above floor) · 12 rejected (below floor · returned to T1 pool)"
sep
say "Partitions emerging from the graph:"
sep
say "${BOLD}Cluster 01 · DMEPOS upcoding (K0823)${RESET}"
say "  ├─ members:       138 NPIs · 1 ZIP cluster center (Houston · 9 ZIP3s)"
say "  ├─ primary fault: ${BOLD}DME-001${RESET} (4.2x national median utilization)"
say "  ├─ supporting:    PREM-001 (14 of 138 also share CMRA premise)"
say "  ├─ rows in scope: ${BOLD}38${RESET} (top-billers above 99.5th percentile)"
say "  ├─ exposure:      ${BOLD}${RED}\$30,000,000${RESET} (sum billed - peer median × utilization)"
say "  ├─ recovery low:  ${BOLD}\$30M${RESET} (30% × allowed amount on MAC overpayment process)"
say "  ├─ recovery high: ${BOLD}\$90M${RESET} (3x FCA treble)"
say "  └─ AVA score:     ${BOLD}0.87${RESET} (defensibility · ESCALATE threshold 0.65)"
sep
say "${BOLD}Cluster 02 · LEIE-excluded provider${RESET}"
say "  ├─ members:       22 NPIs"
say "  ├─ primary fault: ${BOLD}LEIE-001${RESET} (active billing post-exclusion)"
say "  ├─ supporting:    LEIE-004 (9 of 22 also missed reinstatement window)"
say "  ├─ rows in scope: ${BOLD}33${RESET}"
say "  ├─ exposure:      ${BOLD}${RED}\$25,000,000${RESET}"
say "  ├─ recovery low/high: ${BOLD}\$25M / \$75M${RESET}"
say "  └─ AVA score:     ${BOLD}0.94${RESET} (statutory binary · highest tier)"
sep
say "${BOLD}Cluster 03 · Phantom premise${RESET}"
say "  ├─ members:       31 NPIs"
say "  ├─ primary fault: ${BOLD}PREM-001${RESET} (CMRA / virtual office)"
say "  ├─ supporting:    PREM-003 + POS-001 (18 of 31 also have address mismatch + PECOS gap)"
say "  ├─ rows in scope: ${BOLD}28${RESET}"
say "  ├─ exposure:      ${BOLD}${RED}\$20,000,000${RESET}"
say "  ├─ recovery low/high: ${BOLD}\$20M / \$60M${RESET}"
say "  └─ AVA score:     ${BOLD}0.81${RESET} (deterministic match on USPS registry)"
sep
say "${BOLD}Cluster 04 · Multi-year recidivism${RESET}"
say "  ├─ members:       18 NPIs"
say "  ├─ primary fault: ${BOLD}REC-001${RESET} (3+ consecutive year flag)"
say "  ├─ supporting:    REC-002 (9 also have same-NPI outlier in 2+ fiscal years)"
say "  ├─ rows in scope: ${BOLD}33${RESET}"
say "  ├─ exposure:      ${BOLD}${RED}\$25,000,000${RESET}"
say "  ├─ recovery low/high: ${BOLD}\$25M / \$75M${RESET}"
say "  └─ AVA score:     ${BOLD}0.79${RESET} (pattern element for FCA)"
stage_done 3 "AVA clustering" "1.4"
pause 0.4

# ============================================================================
# STAGE 04 · AVA RECOMMENDATION
# ============================================================================
stage_start "04" "AVA recommendation · per-cluster verdict + statutory path"
note "ESCALATE threshold: AVA score >= 0.65 + at least one citable statute."
sep
say "${BOLD}══ The model boundary (Daubert / FRE 902 critical) ══${RESET}"
note "JIL never puts a large language model in the verdict path. Opposing counsel would attack:"
note "  · training-data composition (cannot be reproduced under FRE 702)"
note "  · hallucination rate (>0 · never auditable to known error rate prong)"
note "  · reproducibility (LLMs are stochastic · fails Daubert second prong)"
note "Every verdict reduces to deterministic components below."
sep
say "${BOLD}══ AVA inference stack (model card) ══${RESET}"
say "  ┌─ Component                       Model / library                          Role"
say "  ├─ Cluster construction            NetworkX 3.2 (Louvain, seed=42)          deterministic group"
say "  ├─ Statutory-binary lookup         JIL/statutes-tbl v2026.05.21             deterministic match"
say "  ├─ Evidence-count aggregation      SQL COUNT against T1 findings            deterministic count"
say "  ├─ Judicial-precedent similarity   LegalBERT-base-uncased + curated corpus  ${BOLD}embeddings only${RESET}"
say "  ├─ Time-decay weight               exp(-λ × months_old) · λ=0.05            deterministic formula"
say "  ├─ Multi-year-pattern bonus        SQL EXISTS over fiscal years             deterministic rule"
say "  ├─ Score aggregation               weighted sum (constants below)           deterministic math"
say "  └─ Threshold dispatch              if-else against 0.65 / 0.40              deterministic"
sep
say "${BOLD}Where ML/LLM IS used (operations only · never verdict):${RESET}"
say "  ├─ LegalBERT computes cosine similarity against the ${BOLD}JIL-curated case corpus${RESET}"
say "  │   (3,847 cases · hand-tagged by counsel · versioned · hash-sealed at v2026.05.13)"
say "  ├─ No free-form LLM output enters the verdict pipeline at any point"
say "  ├─ Narrative LLM (Claude Sonnet 4.6) drafts the human-readable CREB summary ONLY"
say "  │   - fact-injected from deterministic JSON · grounded-claim filter rejects unsourced text"
say "  │   - human signoff (SIU director + counsel) required before CREB seal"
say "  ├─ Claude Haiku 4.5 powers in-app SIU-Q&A on already-sealed findings (read-only chat)"
say "  └─ All model versions + prompt hashes + outputs are sealed into the CREB audit trail"
sep
say "${BOLD}══ Defensibility scoring formula ══${RESET}"
say "  AVA score = 0.35 × statutory_binary"
say "            + 0.25 × min(observable_evidence_count / 500, 1.0)"
say "            + 0.20 × judicial_precedent_cosine_sim"
say "            + 0.10 × exp(-0.05 × months_since_event)"
say "            + 0.10 × multi_year_pattern_bonus"
say "  Weights (0.35 · 0.25 · 0.20 · 0.10 · 0.10) constant across engagements · sealed at v2026.05.21"
say "  Re-running with the same inputs returns the same score · byte-identical · forever"
sep

say "${BOLD}══ Cluster 01 score derivation (every term traceable) ══${RESET}"
say "  statutory_binary:               0.70   (FCA pattern · sub-binary in scoring table)"
say "  observable_evidence:             0.92   (138 NPIs × 38 supporting rows / 500 normalizer, capped)"
say "  judicial_precedent_cosine:       0.88   (similarity vs curated FCA-DMEPOS cluster · 12 case anchors)"
say "  time_decay:                      0.64   (exp(-0.05 × 9 months avg) = 0.638)"
say "  multi_year_pattern:              0.00   (Cluster 01 not multi-year · Cluster 04 is)"
say "  ─────────────────────────────────────────────────────────────────"
say "  Weighted sum:  0.35×0.70 + 0.25×0.92 + 0.20×0.88 + 0.10×0.64 + 0.10×0.00 = ${BOLD}0.87${RESET}"
say "  Threshold check: 0.87 ≥ 0.65 → ${INV}${RED} ESCALATE ${RESET}"
ok "${BOLD}Cluster 01 verdict${RESET}: ${INV}${RED} ESCALATE ${RESET} · FCA §3729 · per-claim civil penalty applies"
say "  ├─ Judicial precedent anchors:  US v. Bath Iron Works · US v. Sanford-Brown · US v. Lockheed"
say "  ├─ FCA pathway math:            (\$30M billed × 3 treble) + (\$11,665 × 38 claims) = \$90M + \$443K"
say "  └─ Recommended path:            qui-tam relator + parallel administrative recovery"
sep
ok "  ${INV}${RED} ESCALATE ${RESET} · FCA §3729 · per-claim civil penalty applies"
say "  ├─ Statutory binary:    0.7 (FCA pattern, not binary like LEIE)"
say "  ├─ Observable evidence: 138 NPIs × multiple fiscal years"
say "  ├─ Judicial precedent:  US v. Bath Iron Works · US v. Sanford-Brown · US v. Lockheed"
say "  ├─ FCA pathway:         (\$30M billed × 3) + (\$11,665 × 38 claims) = \$90M + \$443K"
say "  └─ Recommended path:    qui-tam relator + parallel administrative recovery"
sep
say "${BOLD}══ Cluster 02 score derivation ══${RESET}"
say "  statutory_binary:               1.00   (LEIE exclusion is binary / dispositive · 42 USC 1320a-7)"
say "  observable_evidence:             0.84   (22 NPIs × 33 supporting rows / 500 normalizer)"
say "  judicial_precedent_cosine:       0.94   (US v. Mackby + US v. Krizek + 8 LEIE-billing cases)"
say "  time_decay:                      0.71   (exp(-0.05 × 7 months avg))"
say "  multi_year_pattern:              0.00"
say "  ─────────────────────────────────────────────────────────────────"
say "  Weighted sum:  0.35×1.00 + 0.25×0.84 + 0.20×0.94 + 0.10×0.71 + 0.10×0.00 = ${BOLD}0.82${RESET}"
say "  ${DIM}(Earlier draft showed 0.94 from raw statutory weight; current rev applies the 0.35 weight)${RESET}"
say "  Threshold check: 0.82 ≥ 0.65 → ${INV}${RED} ESCALATE ${RESET}"
ok "${BOLD}Cluster 02 verdict${RESET}: ${INV}${RED} ESCALATE ${RESET} · 42 USC 1320a-7 (statutory binary)"
say "  ├─ Judicial precedent anchors:  US v. Mackby · US v. Krizek · US v. Pemberton"
say "  ├─ Pathway:                     administrative recovery · no FCA element required"
say "  └─ Recommended path:            direct MAC overpayment notice + CMS notice of intent"
sep

say "${BOLD}══ Cluster 03 score derivation ══${RESET}"
say "  statutory_binary:               0.85   (42 CFR 424.516 enrollment standards · regulatory binary)"
say "  observable_evidence:             0.78   (31 NPIs × 28 rows + USPS CMRA + CMS POS deterministic match)"
say "  judicial_precedent_cosine:       0.82   (US v. Caremark + US v. Park Avenue Pharmacy + 6 premise cases)"
say "  time_decay:                      0.68   (exp(-0.05 × 8 months avg))"
say "  multi_year_pattern:              0.00"
say "  ─────────────────────────────────────────────────────────────────"
say "  Weighted sum:  0.35×0.85 + 0.25×0.78 + 0.20×0.82 + 0.10×0.68 + 0.10×0.00 = ${BOLD}0.79${RESET}"
say "  Threshold check: 0.79 ≥ 0.65 → ${INV}${RED} ESCALATE ${RESET}"
ok "${BOLD}Cluster 03 verdict${RESET}: ${INV}${RED} ESCALATE ${RESET} · 42 CFR 424.516 (enrollment standards)"
say "  ├─ Judicial precedent anchors:  US v. Caremark · US v. Park Avenue Pharmacy · US v. Krizek"
say "  ├─ FCA pathway:                 materiality element strong (premise = enrollment condition)"
say "  └─ Recommended path:            revocation referral + FCA filing"
sep

say "${BOLD}══ Cluster 04 score derivation ══${RESET}"
say "  statutory_binary:               0.65   (FCA pattern element supports knowledge prong)"
say "  observable_evidence:             0.71   (18 NPIs × 33 rows + multi-year history)"
say "  judicial_precedent_cosine:       0.74   (US v. Health Possibilities + US v. United Tech. + 5 recidivism cases)"
say "  time_decay:                      0.55   (exp(-0.05 × 12 months avg over 3-year window))"
say "  multi_year_pattern:              1.00   (${BOLD}3+ consecutive years${RESET} · pattern bonus fires)"
say "  ─────────────────────────────────────────────────────────────────"
say "  Weighted sum:  0.35×0.65 + 0.25×0.71 + 0.20×0.74 + 0.10×0.55 + 0.10×1.00 = ${BOLD}0.76${RESET}"
say "  Threshold check: 0.76 ≥ 0.65 → ${INV}${RED} ESCALATE ${RESET}"
ok "${BOLD}Cluster 04 verdict${RESET}: ${INV}${RED} ESCALATE ${RESET} · FCA §3729 (pattern + recidivism)"
say "  ├─ Judicial precedent anchors:  US v. Health Possibilities · US v. United Tech. · US v. Bornstein"
say "  ├─ FCA pathway:                 scienter prong strengthened by 3+ year pattern"
say "  └─ Recommended path:            qui-tam relator with consolidated multi-year complaint"
sep

say "${BOLD}══ Daubert prong coverage (why this evidence survives challenge) ══${RESET}"
say "  ├─ ${BOLD}Testable${RESET}:           every T1 check + scoring component re-runnable from sealed inputs"
say "  ├─ ${BOLD}Peer-reviewed${RESET}:      detection methodology published at /attestation-checks (175 checks)"
say "  ├─ ${BOLD}Known error rate${RESET}:   0% false positives in customer report (T2 gates · cross-correlation matrix)"
say "  ├─ ${BOLD}General acceptance${RESET}: methodology matches OIG SIU + MFCU established practice"
say "  ├─ ${BOLD}Methodology applied${RESET}: deterministic provenance per finding (input row hash + check version)"
say "  └─ ${BOLD}Cross-examination${RESET}:  every cluster carries the seed, the weights, the corpus version, the score"
sep
say "${BOLD}Aggregate verdict${RESET}: 4 of 4 clusters → ESCALATE · total exposure ${BOLD}${RED}\$100,000,000${RESET}"
say "Total findings reviewed: 1,847 · clusters formed: 4 · clusters escalated: 4 · false positives: 0"
stage_done 4 "AVA recommendation" "0.6"
pause 0.4

# ============================================================================
# STAGE 05 · TIER 2 SUBSTANTIATION
# ============================================================================
stage_start "05" "Tier 2 substantiation · paid vendor evidence pulls in parallel"
note "Tier 2 is where the vendor proves legitimacy to the MCO."
note "No T1 flag becomes a finding in the customer report without T2 corroboration."
sep
say "Vendor adapter pool: ${BOLD}6 vendors${RESET} · concurrency: ${BOLD}12${RESET} · timeout: 8s per call"
say "Authorization basis: signed MSA on file · per-cluster budget cap enforced server-side"
sep
say "${BOLD}OpenCorporates beneficial-ownership API${RESET}"
say "  ├─ endpoint:     POST api.opencorporates.com/v0.4/officers/search"
say "  ├─ payload:      22 EINs (Cluster 02 LEIE-excluded providers)"
say "  ├─ response:     22/22 200 OK · median 612ms · p95 1.84s"
say "  ├─ matches:      ${BOLD}22${RESET} (4 common-owner rings surfaced across 9 supplier NPIs)"
say "  ├─ evidence pkt: sha256:1f3a9...c8d27 · 47.2KB JSON"
ok "  └─ corroborates: Cluster 02 · Cluster 04 (4 of 18 RECIDIVISM NPIs match a Cluster 02 owner)"
sep
say "${BOLD}OFAC SDN List (paid mirror)${RESET}"
say "  ├─ endpoint:     POST api.sanctions.io/v2/screen"
say "  ├─ payload:      138 NPIs (Cluster 01) + 31 NPIs (Cluster 03) = 169 entities"
say "  ├─ response:     169/169 200 OK · median 234ms"
say "  ├─ matches:      ${BOLD}0${RESET} sanctions hits (clean screen)"
say "  ├─ evidence pkt: sha256:9a2c8...f4eb1"
ok "  └─ corroborates: sanctions-clean ⇒ findings hold under FRE 902 self-authentication"
sep
say "${BOLD}SAM.gov v4 entity-information API${RESET}"
say "  ├─ endpoint:     GET api.sam.gov/entity-information/v4/exclusions"
say "  ├─ payload:      31 UEIs (Cluster 03 phantom-premise entities)"
say "  ├─ response:     31/31 200 OK · median 1.42s · p95 2.31s"
say "  ├─ matches:      ${BOLD}7${RESET} federal exclusions surfaced (beyond OIG LEIE)"
say "  ├─ evidence pkt: sha256:c4e07...37a9d"
ok "  └─ corroborates: Cluster 03 + adds 7 entities to Cluster 02 watchlist"
sep
say "${BOLD}NPPES NPI registry · delta vs FY22 snapshot${RESET}"
say "  ├─ endpoint:     GET npiregistry.cms.hhs.gov/api/?version=2.1"
say "  ├─ payload:      18 NPIs (Cluster 04 recidivism)"
say "  ├─ response:     18/18 200 OK · median 318ms"
say "  ├─ matches:      18 NPIs · 14 with practice-location changes during flag window"
say "  ├─ evidence pkt: sha256:e892b...d1f4c"
ok "  └─ corroborates: 14 NPIs moved premise during flagged period (consistent with phantom-premise)"
sep
say "${BOLD}CMS POS file cross-check${RESET}"
say "  ├─ source:       JIL_DATA.CMS_PUBLIC.CMS_PROVIDER_OF_SERVICES (Snowflake)"
say "  ├─ payload:      31 NPIs (Cluster 03)"
say "  ├─ matches:      ${BOLD}31/31${RESET} have a POS-file mismatch with NPPES practice location"
say "  ├─ evidence pkt: sha256:3a76d...b91e8"
ok "  └─ corroborates: Cluster 03 (deterministic match · regulatory cite anchor)"
sep
say "${BOLD}USPS Commercial Mail Receiving Agency registry${RESET}"
say "  ├─ source:       JIL_DATA.CMS_PUBLIC.USPS_CMRA_PREMISE_REGISTRY"
say "  ├─ payload:      31 practice addresses (Cluster 03)"
say "  ├─ matches:      ${BOLD}31/31${RESET} addresses are CMRA-registered (commercial mail receivers)"
say "  ├─ evidence pkt: sha256:7c2e1...95f0a"
ok "  └─ corroborates: Cluster 03 · authoritative source for premise mismatch"
sep
say "${BOLD}Cross-correlation pass${RESET} (independent corroboration matrix)"
say "  ├─ Cluster 01: 38 cases · DME-001 + DME-007 (intra-T1) + OFAC clean        ${BOLD}${GREEN}substantiated${RESET}"
say "  ├─ Cluster 02: 33 cases · OpenCorporates + SAM.gov + OFAC clean             ${BOLD}${GREEN}substantiated${RESET}"
say "  ├─ Cluster 03: 28 cases · POS + CMRA + SAM.gov                              ${BOLD}${GREEN}substantiated${RESET}"
say "  └─ Cluster 04: 33 cases · NPPES + OpenCorporates owner-ring                 ${BOLD}${GREEN}substantiated${RESET}"
sep
say "${BOLD}T2 outcome${RESET}: ${BOLD}132 of 132${RESET} cases substantiated · ${BOLD}${GREEN}0 false positives${RESET} reaching customer report"
say "Vendor + ops cost: \$168K (${DIM}bundled in annual run fee under v4.0 MCO TAM${RESET})"
sep
say "${BOLD}══ Narrative generator (operations only · never in verdict path) ══${RESET}"
say "  ├─ Model:              ${BOLD}Claude Sonnet 4.6${RESET} (Anthropic Bedrock · us-east-1 · jil-ava IAM role)"
say "  ├─ Inference profile:  arn:aws:bedrock:us-east-1::sealed/jil-creb-narrative-v4-stable"
say "  ├─ Role:               drafts human-readable summary embedded in the CREB document"
say "  ├─ Inputs:             deterministic JSON facts only (findings + statutes + scoring math)"
say "  ├─ Prompt template:    ${BOLD}jil_creb_narrative_v3.2${RESET} · frozen · sha256:fa83c...d12e8"
say "  ├─ Temperature:        0.2 (low-variance · grounded-claim filter rejects unsourced text)"
say "  ├─ Output validation:  JSON-schema check · every claim must cite a finding_id or statute_id"
say "  ├─ Human signoff:      SIU director + counsel review BEFORE the CREB is sealed (Tier 3)"
say "  └─ Audit trail:        model version + temperature + prompt hash + output hash sealed in CREB"
sep
say "${BOLD}══ What does NOT use AI ══${RESET}"
say "  ├─ T1 check execution (deterministic SQL + rules)"
say "  ├─ Cluster construction (Louvain modularity · seed=42)"
say "  ├─ Defensibility scoring (weighted formula · constants sealed)"
say "  ├─ Threshold dispatch (if/else against 0.65 / 0.40)"
say "  ├─ FCA pathway math (deterministic formula)"
say "  └─ CREB Merkle seal (BLAKE3 + ed25519 · no inference at all)"
stage_done 5 "Tier 2 substantiation" "4.7"
pause 0.4

# ============================================================================
# STAGE 06 · CREB SEAL
# ============================================================================
stage_start "06" "CREB seal · FRE 902(13) self-authenticating · 14-of-20 BFT signed"
spin_for 0.4 "computing Merkle tree + collecting validator signatures"
say "Bundle composition: ${BOLD}132 cases${RESET} (38 + 33 + 28 + 33) across 4 clusters"
say "Per-case payload:   findings record · T1 check version · T2 evidence packets · statutory cites · supporting docs"
say "Bundle template:    ${BOLD}mco_creb_v1${RESET}    structure version: 2026.05.13"
sep
say "${BOLD}Merkle tree construction${RESET}"
say "  ├─ Leaves:       132 (one per case · BLAKE3 hash)"
say "  ├─ Tree depth:   8 levels (132 → 66 → 33 → 17 → 9 → 5 → 3 → 2 → 1)"
say "  ├─ Root hash:    ${CYAN}0x8a13f4c7d2e0a91b8c93e2 ...${RESET}"
say "  └─ Compute time: 142ms on single core"
sep
say "${BOLD}Validator quorum collection${RESET} (14-of-20 BFT threshold · 13+ jurisdictions)"
ok "  ${BOLD}val-genesis${RESET} (DE)  signed at 14:32:11.224  ed25519:f8b3a...e91c4"
ok "  ${BOLD}val-us${RESET}      (US-east) signed at 14:32:11.318  ed25519:7d2c9...4f8a1"
ok "  ${BOLD}val-de${RESET}      (DE-west) signed at 14:32:11.394  ed25519:c1e94...82b7d"
ok "  ${BOLD}val-eu${RESET}      (EU)      signed at 14:32:11.456  ed25519:a93f1...e6d28"
ok "  ${BOLD}val-sg${RESET}      (SG)      signed at 14:32:11.519  ed25519:5e0b8...c47d2"
ok "  ${BOLD}val-ch${RESET}      (CH)      signed at 14:32:11.583  ed25519:b62d4...a91f3"
ok "  ${BOLD}val-jp${RESET}      (JP)      signed at 14:32:11.642  ed25519:7c91d...3f0a8"
ok "  ${BOLD}val-gb${RESET}      (GB)      signed at 14:32:11.704  ed25519:e3a7b...d1248"
ok "  ${BOLD}val-ae${RESET}      (AE)      signed at 14:32:11.768  ed25519:2f481...c9b73"
ok "  ${BOLD}val-br${RESET}      (BR)      signed at 14:32:11.831  ed25519:9d4a2...b7e51"
ok "  ${BOLD}val-au${RESET}      (AU)      signed at 14:32:11.894  ed25519:6c819...f0d2a"
ok "  ${BOLD}val-ca${RESET}      (CA)      signed at 14:32:11.957  ed25519:1e8d3...49a02"
ok "  ${BOLD}val-kr${RESET}      (KR)      signed at 14:32:12.018  ed25519:c4f08...3b219"
ok "  ${BOLD}val-mx${RESET}      (MX)      signed at 14:32:12.080  ed25519:5a23d...e708f"
say "  ${DIM}val-cl, val-za, val-il, val-no, val-tw, val-in${RESET}  ${DIM}offline / standby (BFT tolerates 6)${RESET}"
say "  Threshold met:  ${BOLD}14 of 20${RESET} signatures collected"
sep
say "${BOLD}CourtChain anchor${RESET}"
say "  ├─ L1 block:        14,289,317"
say "  ├─ Anchor tx hash:  ${CYAN}0xfb2c91e8a3470d2c5d8f1c7b...${RESET}"
say "  ├─ Block finality:  5.84s (target <6s)"
say "  ├─ Gas / fees:      protocol-level (0 customer USD)"
say "  └─ Verifiable at:   ${CYAN}https://jilsovereign.com/verify?merkle=8a13f4c7...${RESET}"
sep
say "${BOLD}FRE 902(13) certification appendix${RESET}"
say "  ├─ Certifying officer:    JIL Sovereign Technologies, Inc. (custodian)"
say "  ├─ Authenticity statement: cryptographically signed digital records"
say "  ├─ Process attestation:    deterministic detection · documented check versions"
say "  └─ Admissible:             ${BOLD}without custodian testimony${RESET}"
sep
say "${BOLD}Bundle artifact${RESET}"
say "  ├─ Format:        signed PDF + JSON-LD machine-readable twin"
say "  ├─ File size:     12.4 MB compressed · 47.8 MB expanded"
say "  ├─ Retention:     ${BOLD}15+ years${RESET} on CourtChain · customer copy in SDV"
say "  └─ Distribution:  MAC overpayment workflow · OIG referral queue · counsel hand-off"
sep
say "${BOLD}CREB fee at full approval${RESET}: ${BOLD}${GOLD}\$10,000,000${RESET}  (10% × \$100M · \$250K floor / bundle)"
say "Triggers on customer seal-and-deliver acceptance · not on detection · not on recovery"
stage_done 6 "CREB seal" "1.1"

END=$(date +%s.%N)
ELAPSED=$(awk "BEGIN{printf \"%.1f\", $END - $START}")

# ============================================================================
# MONEY STORY
# ============================================================================
if [[ $JSON -eq 1 ]]; then
  printf '{"summary":{"total_exposure_usd":100000000,"recovery_low_usd":100000000,"recovery_high_usd":300000000,"creb_fee_usd":10000000,"fca_if_unpursued_usd":300000000,"roi_low":10,"clusters":4,"cases":132,"false_positives":0,"elapsed_seconds":%s}}\n' "$ELAPSED"
  exit 0
fi

printf "\n${BOLD}${NAVY}══════════════════════════════════════════════════════════════════════════${RESET}\n"
printf "  ${BOLD}${RED}\$100.00M${RESET} total exposure  ·  ${BOLD}4 clusters${RESET}  ·  ${BOLD}132 cases${RESET} substantiated\n"
printf "  Pursuing yields ${BOLD}${GREEN}~10×${RESET} on the CREB fee at the low band\n"
printf "${BOLD}${NAVY}══════════════════════════════════════════════════════════════════════════${RESET}\n\n"

printf "  ${DIM}Total exposure   ${RESET} ${BOLD}${RED}\$100.00M${RESET}\n"
printf "  ${DIM}Recovery (low)   ${RESET} ${BOLD}${GREEN}\$100.00M${RESET}\n"
printf "  ${DIM}Recovery (high)  ${RESET} ${BOLD}${GREEN}\$300.00M${RESET}\n"
printf "  ${DIM}CREB fee (10%%)   ${RESET} ${BOLD}${GOLD}\$ 10.00M${RESET}\n"
printf "  ${DIM}FCA if unpursued ${RESET} ${BOLD}${RED}\$300.00M${RESET}\n"
printf "  ${DIM}ROI low band     ${RESET} ${BOLD}10×${RESET}\n\n"

printf "  Customer pays the ${BOLD}\$10M CREB fee${RESET} at full approval.\n"
printf "  Recovers ${BOLD}\$100M-\$300M${RESET} through MAC overpayment or FCA litigation.\n"
printf "  ${BOLD}Nets \$90M-\$290M${RESET} after JIL's fee.\n\n"

printf "  Compared to outside counsel + forensic accountants (typically 25-33%% of recoveries),\n"
printf "  JIL at 10%% is roughly ${BOLD}one-third the cost${RESET} and faster.\n\n"

printf "  ${DIM}See it live:${RESET}\n"
printf "    ${CYAN}https://customer.jilsovereign.com/ava/eng-mco-dmepos-2024-showcase${RESET}\n\n"
printf "  ${DIM}POC on your own data:${RESET}\n"
printf "    ${CYAN}https://jilsovereign.com/contact?product=mco&intent=poc${RESET}\n\n"
printf "  ${DIM}Walkthrough elapsed: %ss${RESET}\n\n" "$ELAPSED"
