/**
 * AS/PLATFORM/2026/007 — Wave 1 behavioral proof — Compliance/Assurance SUBSTRATE.
 *
 * Re-grounds (does NOT grandfather) the AS/PLATFORM/2026/006 make-real claim that
 * compliance status DERIVES from a real, persisted check run rather than a
 * hardcoded/synthetic verdict. Paired POS/NEG (Rule 18), run through the REAL
 * aegis_app RLS path (runComplianceChecks/getLatestRun use `db` = appPool inside
 * runWithTenantContext). DEV-ONLY (Rule 17: dev verdict ≠ prod verdict).
 *
 * Covered set (shared sink = compliance_check_runs/results via getLatestRun):
 *   compliance-checks (substrate) + the derivation cluster that reads getLatestRun:
 *   compliance-dashboard, compliance-reporter, soc2-evidence, uganda-compliance,
 *   security-scorecard(compliance dim). This harness proves the substrate +
 *   derivation honest-gap; per-module status-map fidelity is a code-read item.
 *
 * Legs:
 *   POS-1  default deps, persist  → real verdicts from live state, run persists,
 *          read-back via getLatestRun matches (record-of-truth).
 *   NEG-1  inject failing fieldRoundTrip → field_encryption_active flips PASS→FAIL
 *          (verdict reflects injected real-state, not a hardcoded PASS).
 *   NEG-2  inject non-conforming getRlsConformance → rls_tenant_isolation PASS→FAIL.
 *   NEG-3  getLatestRun(never-run tenant) → null  (derivation input is honestly
 *          absent; deriveLatestRun returns empty map → NOT_ASSESSED, not green).
 *
 * Run: npx tsx scripts/vf-w1-compliance-substrate-proof.ts
 */
import {
  runComplianceChecks,
  getLatestRun,
  CHECK_IDS,
  defaultDeps,
  type RlsConformance,
} from "../server/lib/compliance-checks";
import { verifyChainIntegrity } from "../server/lib/audit-chain";

const POS_TENANT = "aegis-sovereign"; // real dev tenant
const EMPTY_TENANT = "vf-w1-empty-zzz"; // never-run tenant (SELECT only, no insert)

let failures = 0;
function check(label: string, cond: boolean, detail: string) {
  const tag = cond ? "PASS" : "FAIL";
  if (!cond) failures++;
  console.log(`  [${tag}] ${label} — ${detail}`);
}

function statusOf(results: { id: string; status: string }[], id: string): string {
  return results.find((r) => r.id === id)?.status ?? "<missing>";
}

async function main() {
  console.log("== AS/PLATFORM/2026/007 W1 — compliance substrate paired proof (DEV, aegis_app path) ==\n");

  // ── POS-1: default deps, persist; real verdicts from live state ────────────
  console.log("POS-1: runComplianceChecks(default deps, persist=true) for", POS_TENANT);
  const pos = await runComplianceChecks({
    tenantId: POS_TENANT,
    runType: "vf-w1-proof",
    triggeredBy: "vf-w1-harness",
    persist: true,
  });
  check("run persisted (runId non-null)", pos.runId !== null, `runId=${pos.runId}`);
  check("total checks > 0", pos.summary.total > 0, `total=${pos.summary.total}`);
  check("RLS isolation PASS", statusOf(pos.results, CHECK_IDS.RLS_TENANT_ISOLATION) === "PASS", statusOf(pos.results, CHECK_IDS.RLS_TENANT_ISOLATION));
  check("field encryption PASS", statusOf(pos.results, CHECK_IDS.FIELD_ENCRYPTION) === "PASS", statusOf(pos.results, CHECK_IDS.FIELD_ENCRYPTION));
  check("PII encryption PASS", statusOf(pos.results, CHECK_IDS.PII_FIELD_ENCRYPTION) === "PASS", statusOf(pos.results, CHECK_IDS.PII_FIELD_ENCRYPTION));
  // Audit-chain verdict must MIRROR independently-computed ground truth (not assumed PASS):
  // valid chain → PASS, broken chain → FAIL. This proves the check tracks real state both ways.
  const gt = await verifyChainIntegrity();
  const expectedAudit = gt.valid ? "PASS" : "FAIL";
  check(
    `audit chain mirrors ground truth (chain valid=${gt.valid}${gt.valid ? "" : ` brokenAt=${gt.brokenAt}`})`,
    statusOf(pos.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY) === expectedAudit,
    `check=${statusOf(pos.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY)} expected=${expectedAudit}`,
  );
  check("required secrets PASS", statusOf(pos.results, CHECK_IDS.REQUIRED_SECRETS) === "PASS", statusOf(pos.results, CHECK_IDS.REQUIRED_SECRETS));
  check("vuln scan honestly NOT_ASSESSED", statusOf(pos.results, CHECK_IDS.VULNERABILITY_SCAN) === "NOT_ASSESSED", statusOf(pos.results, CHECK_IDS.VULNERABILITY_SCAN));

  // read-back the persisted run (RLS-scoped, aegis_app)
  const readback = await getLatestRun(POS_TENANT);
  check("getLatestRun returns the persisted run", !!readback && readback.run.id === pos.runId, `latest=${readback?.run.id}`);
  check("read-back result rows match run", !!readback && readback.results.length === pos.summary.total, `rows=${readback?.results.length}`);
  check("read-back sourceDigest matches", !!readback && readback.run.sourceDigest === pos.sourceDigest, `digest match=${readback?.run.sourceDigest === pos.sourceDigest}`);

  // ── NEG-1: inject failing fieldRoundTrip → field_encryption_active FAIL ─────
  console.log("\nNEG-1: inject failing fieldRoundTrip (available=true, ok=false)");
  const neg1 = await runComplianceChecks({
    tenantId: POS_TENANT,
    persist: false,
    deps: {
      fieldRoundTrip: () => ({ available: true, ok: false, encrypted: false, matched: false, algorithm: "", keyLength: 0, keySource: "", error: "vf-w1 injected fault" }),
    },
  });
  check("field encryption flips to FAIL", statusOf(neg1.results, CHECK_IDS.FIELD_ENCRYPTION) === "FAIL", statusOf(neg1.results, CHECK_IDS.FIELD_ENCRYPTION));
  check("other check unaffected (PII still PASS)", statusOf(neg1.results, CHECK_IDS.PII_FIELD_ENCRYPTION) === "PASS", statusOf(neg1.results, CHECK_IDS.PII_FIELD_ENCRYPTION));

  // ── NEG-2: inject non-conforming RLS → rls_tenant_isolation FAIL ───────────
  console.log("\nNEG-2: inject non-conforming getRlsConformance (allConform=false)");
  const badRls: RlsConformance = {
    expected: 79, found: 78, conforming: 78,
    missing: ["vf_w1_phantom_table"], nonConforming: [],
    rlsDisabledTables: [], roleAttributes: { role: "aegis_app", superuser: false, bypassRls: false, inherit: false }, roleOk: true,
    allConform: false,
  };
  const neg2 = await runComplianceChecks({
    tenantId: POS_TENANT,
    persist: false,
    deps: { getRlsConformance: async () => badRls },
  });
  check("RLS isolation flips to FAIL", statusOf(neg2.results, CHECK_IDS.RLS_TENANT_ISOLATION) === "FAIL", statusOf(neg2.results, CHECK_IDS.RLS_TENANT_ISOLATION));

  // ── NEG-3: derivation input honestly absent for a never-run tenant ─────────
  console.log("\nNEG-3: getLatestRun(never-run tenant) → null (derivation has nothing to fabricate from)");
  const empty = await getLatestRun(EMPTY_TENANT);
  check("never-run tenant yields null run", empty === null, `latest=${empty === null ? "null" : "<row!>"}`);

  // ── AUDIT-A: inject a VALID chain → audit_chain_integrity PASS (proves the PASS
  //    branch deterministically, independent of the live dev chain; persist=false). ─
  console.log("\nAUDIT-A: inject verifyChainIntegrity()->valid → audit chain must PASS");
  const auditValid = await runComplianceChecks({
    tenantId: POS_TENANT,
    persist: false,
    deps: {
      verifyChainIntegrity: (async () => ({
        valid: true, totalEntries: 100, lastHash: "vf-w1-injected-valid",
      })) as typeof verifyChainIntegrity,
    },
  });
  check("audit chain PASS on injected-VALID chain", statusOf(auditValid.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY) === "PASS", statusOf(auditValid.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY));

  // ── AUDIT-B: inject a BROKEN chain → audit_chain_integrity FAIL (deterministic) ──
  console.log("\nAUDIT-B: inject verifyChainIntegrity()->broken → audit chain must FAIL");
  const auditBroken = await runComplianceChecks({
    tenantId: POS_TENANT,
    persist: false,
    deps: {
      verifyChainIntegrity: (async () => ({
        valid: false, totalEntries: 100, brokenAt: 999, brokenReason: "vf-w1 injected break",
      })) as typeof verifyChainIntegrity,
    },
  });
  check("audit chain FAIL on injected-BROKEN chain", statusOf(auditBroken.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY) === "FAIL", statusOf(auditBroken.results, CHECK_IDS.AUDIT_CHAIN_INTEGRITY));

  console.log(`\n== RESULT: ${failures === 0 ? "ALL LEGS PASS" : failures + " LEG(S) FAILED"} ==`);
  process.exit(failures === 0 ? 0 : 1);
}

main().catch((e) => {
  console.error("HARNESS ERROR:", e);
  process.exit(2);
});
