/**
 * vf-w6c-pilot-readiness-substrate-proof.ts
 * AS/PLATFORM/2026/007 — Full-Platform Verification Sweep, WAVE W6c.
 * Surface: pilot-readiness "check/drill/scan/test" suite + its aggregators + ussd-api.
 *
 * This harness BEHAVIORALLY grounds the W6c verdicts. It is VERIFICATION-ONLY:
 * it asserts what the existing code DOES, remediates nothing, and self-cleans.
 *
 * ── What each group proves (Rule 18: every denial paired with a positive) ──
 *
 * GROUP A — REAL/VERIFIED (dev). In-process, role-axis N/A (these read the live
 *   pg catalog / run real DB probes; the tables they touch are GLOBAL non-RLS
 *   platform tables, no tenant_id):
 *     A1/A1b  runChaosDrill  — 6 steps, each `ok` DERIVED from a real DB query
 *             (SELECT 1 / pg_sleep / COUNT rate_limit_events / COUNT audit_logs /
 *             COUNT active users). passed = all-ok && within budget.
 *     A2      runChaosDrill run twice ⇒ ok-vector STABLE (derived from real
 *             state, NOT random) — the positive half of the discriminator that
 *             the GROUP-B fabricators fail.
 *     A3/A3b  runTenantIsolationTest — performs REAL catalog reads
 *             (information_schema.columns / pg_class.relrowsecurity /
 *             pg_policies / pg_proc current_tenant_id); totalChecks>0 (not the
 *             vacuous-pass shape) and details reflect the live schema.
 *
 * GROUP B — FABRICATED, family-2 "random-as-data", behaviorally proven via
 *   NON-DETERMINISM. A real measurement is stable for identical input; these
 *   produce a different persisted/returned metric every call ⇒ the number is
 *   Math.random(), not an observation. Role-axis N/A (GLOBAL non-RLS tables):
 *     B1  runRansomwareDrill.recoveryRtoMin   (persisted receipt)
 *     B2  evaluateSla.observations[].observedMs (computed; dryRun=no persist)
 *     B3  runBreachSlaDrill.notificationLatencyMs (persisted receipt)
 *
 * GROUP C — AGGREGATION CONTAMINATION. computeComplianceScore is REAL arithmetic
 *   (round(passed/total*100) − penalties over 20 DRILL_TABLES) but it reads each
 *   drill's latest `passed` column — INCLUDING the fabricated drills proven in
 *   GROUP B. C1/C2 drive a controlled fabricated breach_sla_drill receipt
 *   (passed 0 ⇒ "fail", passed 1 ⇒ "pass") and show the top-line score follows
 *   it. Role-axis N/A (GLOBAL non-RLS tables).
 *
 * GROUP D — sla_breach_records is the ONE W6c table with tenant_id AND RLS
 *   enrollment (rls-init.ts:118). Its writer scanSlaBreaches fabricates content
 *   (random actuals over a hardcoded 4-tenant list, code-read). Here the RLS
 *   ISOLATION of the table itself is proven AS THE REAL RLS-SUBJECT ROLE
 *   `aegis_app` via withTenantRls (appPool + LOCAL set_config GUC, NOT SET ROLE):
 *     D0  current_user === 'aegis_app' inside the phase
 *     D1  POS own-tenant read sees the row
 *     D2  NEG cross-tenant read (tenant B sees 0)
 *     D3  NEG WITH CHECK rejects cross-tenant insert (GUC=A, row tenant=B)
 *     D4  POS WITH CHECK accepts matching-tenant insert
 *
 * Env: DEV (Rule 17 — non-transitive; dev verdict only). Synthetic, self-cleaning
 * (marker VF-W6C). No secret values printed.
 * Run: npx tsx scripts/vf-w6c-pilot-readiness-substrate-proof.ts
 */
import { sql, eq, like } from "drizzle-orm";
import { auditDb, withTenantRls, type DrizzleDb } from "../server/db";
import { runChaosDrill } from "../server/lib/pilot-readiness-extras";
import { runTenantIsolationTest } from "../server/lib/pilot-readiness";
import { runBreachSlaDrill } from "../server/lib/pilot-readiness-extras-2";
import { runRansomwareDrill } from "../server/lib/pilot-readiness-extras-7";
import { evaluateSla } from "../server/lib/pilot-readiness-extras-11";
import { computeComplianceScore } from "../server/lib/pilot-readiness-extras-5";
import { chaosDrillRuns } from "../shared/schema-pilot-extras";
import { breachSlaDrillRuns } from "../shared/schema-pilot-extras-2";
import { ransomwareDrills } from "../shared/schema-pilot-extras-7";
import { complianceScores } from "../shared/schema-pilot-extras-5";
import { slaBreachRecords } from "../shared/schema-pilot-extras-4";
import { slaThresholds } from "../shared/schema-pilot-extras-11";
import { securityTestRuns } from "../shared/schema-rbac";

const MARK = "VF-W6C";
let pass = 0;
let fail = 0;
const lines: string[] = [];
function check(name: string, cond: boolean, detail = "") {
  if (cond) {
    pass++;
    lines.push(`  PASS  ${name}${detail ? ` — ${detail}` : ""}`);
  } else {
    fail++;
    lines.push(`  FAIL  ${name}${detail ? ` — ${detail}` : ""}`);
  }
}
const distinct = (arr: any[]) => new Set(arr.map((x) => JSON.stringify(x))).size;

async function cleanup() {
  const safe = async (p: Promise<any>) => { try { await p; } catch { /* table-shape tolerant */ } };
  await safe(auditDb.delete(chaosDrillRuns).where(like(chaosDrillRuns.triggeredBy, `${MARK}%`)));
  await safe(auditDb.delete(breachSlaDrillRuns).where(like(breachSlaDrillRuns.triggeredBy, `${MARK}%`)));
  await safe(auditDb.delete(ransomwareDrills).where(like(ransomwareDrills.ranBy, `${MARK}%`)));
  await safe(auditDb.delete(complianceScores).where(like(complianceScores.computedBy, `${MARK}%`)));
  await safe(auditDb.delete(slaBreachRecords).where(like(slaBreachRecords.sloName, `${MARK}%`)));
  await safe(auditDb.delete(slaThresholds).where(like(slaThresholds.metricKey, `vf_w6c_%`)));
  await safe(auditDb.delete(securityTestRuns).where(like(securityTestRuns.triggeredBy, `${MARK}%`)));
}

async function main() {
  await cleanup();

  // ===================== GROUP A — REAL/VERIFIED (dev) =====================
  const chaos1: any = await runChaosDrill(`${MARK}-CHAOS`, "primary_db_stall");
  check(
    "A1 runChaosDrill emits 6 real-DB-probe steps",
    Array.isArray(chaos1.steps) && chaos1.steps.length === 6,
    `steps=${chaos1.steps?.length}`,
  );
  check(
    "A1b runChaosDrill step results DERIVED from real DB (all ok, passed=true)",
    chaos1.steps.every((s: any) => s.ok === true) && chaos1.passed === true,
    `passed=${chaos1.passed}`,
  );
  const chaos2: any = await runChaosDrill(`${MARK}-CHAOS`, "primary_db_stall");
  const okVec1 = chaos1.steps.map((s: any) => s.ok).join(",");
  const okVec2 = chaos2.steps.map((s: any) => s.ok).join(",");
  check(
    "A2 runChaosDrill ok-vector STABLE across identical runs (real-state, not random)",
    okVec1 === okVec2 && chaos2.steps.every((s: any) => s.ok === true),
    `both runs all-ok`,
  );

  const iso: any = await runTenantIsolationTest(`${MARK}-ISO`);
  check(
    "A3 runTenantIsolationTest actually ran catalog checks (totalChecks>0, not vacuous-pass)",
    iso.totalChecks > 0 && Array.isArray(iso.details) && iso.details.length > 0,
    `totalChecks=${iso.totalChecks}`,
  );
  const reflectsCatalog =
    iso.details.some((d: any) => d.check === "tenant_id_column_exists" && d.pass === true) &&
    iso.details.some((d: any) => /^rls_enabled_on_|^rls_policies_exist_on_/.test(d.check));
  check(
    "A3b runTenantIsolationTest details reflect the LIVE pg catalog (tenant_id col + RLS/policy probes)",
    reflectsCatalog,
    iso.details.map((d: any) => d.check).join("|").slice(0, 90),
  );

  // ===================== GROUP B — FABRICATED (family-2, non-determinism) ===
  const N = 6;
  const rtos: number[] = [];
  for (let i = 0; i < N; i++) {
    const r: any = await runRansomwareDrill({ ransomDemandUgx: 1_000_000, ranBy: `${MARK}-RANSOM` });
    rtos.push(r.recoveryRtoMin);
  }
  check(
    "B1 runRansomwareDrill recoveryRtoMin NON-DETERMINISTIC for identical input (Math.random, not measurement)",
    distinct(rtos) > 1,
    `distinct=${distinct(rtos)}/${N} vals=[${rtos.join(",")}]`,
  );

  // evaluateSla reads sla_thresholds(enabled=1); seed two synthetic ones so the leg is deterministic.
  await auditDb.delete(slaThresholds).where(like(slaThresholds.metricKey, `vf_w6c_%`));
  await auditDb.insert(slaThresholds).values([
    { metricKey: "vf_w6c_m1", displayName: "VF W6C M1", thresholdMs: 1000, updatedBy: MARK },
    { metricKey: "vf_w6c_m2", displayName: "VF W6C M2", thresholdMs: 2000, updatedBy: MARK },
  ]);
  const vecs: number[][] = [];
  for (let i = 0; i < N; i++) {
    const e: any = await evaluateSla({ dryRun: true });
    vecs.push((e.observations as any[]).map((o) => o.observedMs));
  }
  check(
    "B2 evaluateSla observedMs vector NON-DETERMINISTIC across runs (synthetic random sampler; dryRun=no persist)",
    distinct(vecs) > 1,
    `distinct=${distinct(vecs)}/${N} thresholds=${vecs[0]?.length}`,
  );

  for (let i = 0; i < N; i++) await runBreachSlaDrill(`${MARK}-BREACH`);
  const blat = await auditDb
    .select({ l: breachSlaDrillRuns.notificationLatencyMs })
    .from(breachSlaDrillRuns)
    .where(eq(breachSlaDrillRuns.triggeredBy, `${MARK}-BREACH`));
  check(
    "B3 runBreachSlaDrill notificationLatencyMs NON-DETERMINISTIC (250+random*500, PERSISTED as receipt)",
    new Set(blat.map((x) => x.l)).size > 1,
    `distinct=${new Set(blat.map((x) => x.l)).size}/${blat.length}`,
  );

  // ===================== GROUP C — AGGREGATION CONTAMINATION ===============
  // Remove the GROUP-B breach rows so our controlled receipt is the latest for its key.
  await auditDb.delete(breachSlaDrillRuns).where(like(breachSlaDrillRuns.triggeredBy, `${MARK}%`));
  const baseRow = {
    breachId: `${MARK}-c`, notificationsSent: 4, slaWindowHours: 72,
    notificationLatencyMs: 300, templatesValidated: 4, durationMs: 1,
    detailsJson: "{}", triggeredBy: `${MARK}-CSCORE`,
  };
  // Future createdAt guarantees "latest by createdAt desc" regardless of any concurrent inserts.
  await auditDb.insert(breachSlaDrillRuns).values({ ...baseRow, passed: 0, createdAt: new Date(Date.now() + 10 * 60_000) });
  const scoreNeg: any = await computeComplianceScore({ computedBy: `${MARK}-CSCORE` });
  const bNeg = (scoreNeg.breakdown as any[]).find((b) => b.key === "breach_sla_drill");
  check(
    "C1 computeComplianceScore READS the fabricated drill column — passed=0 latest ⇒ status 'fail'",
    bNeg?.status === "fail",
    `breach_sla_drill=${bNeg?.status}`,
  );
  await auditDb.insert(breachSlaDrillRuns).values({ ...baseRow, passed: 1, createdAt: new Date(Date.now() + 11 * 60_000) });
  const scorePos: any = await computeComplianceScore({ computedBy: `${MARK}-CSCORE` });
  const bPos = (scorePos.breakdown as any[]).find((b) => b.key === "breach_sla_drill");
  check(
    "C2 computeComplianceScore READS the fabricated drill column — passed=1 latest ⇒ status 'pass'",
    bPos?.status === "pass",
    `breach_sla_drill=${bPos?.status}`,
  );
  check(
    "C3 top-line score is REAL arithmetic over (fabricated) inputs (numeric totalScore; rollup denominator = breakdown length = 20 DRILL_TABLES)",
    typeof scorePos.totalScore === "number" &&
      scorePos.drillsTotal === 20 &&
      scorePos.drillsTotal === (scorePos.breakdown as any[]).length,
    `totalScore=${scorePos.totalScore} drillsTotal=${scorePos.drillsTotal} breakdown.len=${(scorePos.breakdown as any[]).length}`,
  );

  // ===================== GROUP D — sla_breach_records RLS as aegis_app ======
  const TA = `${MARK}-tenant-a`;
  const TB = `${MARK}-tenant-b`;
  const probeRow = (tenantId: string) => ({
    tenantId, sloName: `${MARK}-PROBE`, sloTarget: "x", actualValue: "y",
    breachSeverity: "warning", breachStartedAt: new Date(),
  });
  let dRole = "";
  await withTenantRls(TA, async (tx: DrizzleDb) => {
    const who: any = await tx.execute(sql`SELECT current_user AS u`);
    dRole = who.rows?.[0]?.u;
    await tx.insert(slaBreachRecords).values(probeRow(TA));
  });
  check("D0 RLS legs run as aegis_app (real RLS-subject role, not owner/bypass)", dRole === "aegis_app", `current_user=${dRole}`);

  let aSees = -1;
  await withTenantRls(TA, async (tx: DrizzleDb) => {
    const r = await tx.select().from(slaBreachRecords).where(eq(slaBreachRecords.sloName, `${MARK}-PROBE`));
    aSees = r.length;
  });
  check("D1 POS own-tenant read sees the row (aegis_app + GUC=A)", aSees >= 1, `A sees ${aSees}`);

  let bSees = -1;
  await withTenantRls(TB, async (tx: DrizzleDb) => {
    const r = await tx.select().from(slaBreachRecords).where(eq(slaBreachRecords.sloName, `${MARK}-PROBE`));
    bSees = r.length;
  });
  check("D2 NEG cross-tenant read — tenant B sees 0 (RLS USING isolation)", bSees === 0, `B sees ${bSees}`);

  let rejected = false;
  try {
    await withTenantRls(TA, async (tx: DrizzleDb) => {
      await tx.insert(slaBreachRecords).values(probeRow(TB)); // GUC=A, row tenant=B
    });
  } catch {
    rejected = true;
  }
  check("D3 NEG WITH CHECK rejects cross-tenant insert (GUC=A, row tenant=B)", rejected, rejected ? "rejected" : "NOT rejected");

  let accepted = false;
  try {
    await withTenantRls(TA, async (tx: DrizzleDb) => {
      await tx.insert(slaBreachRecords).values(probeRow(TA)); // GUC=A, row tenant=A
    });
    accepted = true;
  } catch { /* ignore */ }
  check("D4 POS WITH CHECK accepts matching-tenant insert (GUC=A, row tenant=A)", accepted, accepted ? "accepted" : "rejected");

  await cleanup();
  lines.push("");
  lines.push(`W6c pilot-readiness substrate proof: ${pass} PASS / ${fail} FAIL`);
  console.log(lines.join("\n"));
  process.exit(fail === 0 ? 0 : 1);
}

main().catch(async (e) => {
  console.error(e);
  try { await cleanup(); } catch { /* ignore */ }
  process.exit(1);
});
