/**
 * Offline proof that the RFC-3161 anchor module verifies a REAL TSA token correctly, both directions.
 * Reads the vendored fixture (tests/fixtures/rfc3161/freetsa-token.json — a genuine token captured
 * from freeTSA.org over anchorDigest(entryCount, headHash)); no network needed. Mirrors the intent of
 * scripts/verify-mldsa65-engine.ts (prove the crypto against a real artifact, not just that it compiles).
 *
 * Run: DATABASE_URL=postgres://u:p@localhost/x AEGIS_APP_DB_PASSWORD=x npx tsx scripts/verify-rfc3161-anchor.ts
 * (DB env is a dummy — the module imports the db pool lazily; verifyAnchor never queries.)
 */
import { readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));

process.env.DATABASE_URL ||= "postgres://u:p@localhost:5432/x";
process.env.AEGIS_APP_DB_PASSWORD ||= "x";

async function main() {
  const { verifyAnchor, isTsaConfigured, tsaAnchorStatus } = await import("../server/lib/rfc3161-anchor");
  const fx = JSON.parse(readFileSync(join(__dirname, "..", "tests", "fixtures", "rfc3161", "freetsa-token.json"), "utf8"));

  const checks: Array<[string, boolean]> = [];

  // 1) Real token verifies over the head it anchors.
  const good = verifyAnchor(fx.tokenB64, fx.entryCount, fx.headHash);
  checks.push(["good token: valid", good.valid === true]);
  checks.push(["good token: signature valid", good.signatureValid === true]);
  checks.push(["good token: covers head", good.messageImprintMatches === true]);
  checks.push(["good token: has genTime", !!good.genTime]);
  checks.push(["good token: TSA name present", !!good.tsaName && good.tsaName !== "(unknown)"]);

  // 2) Wrong head → signature still authentic, but token does NOT cover it → invalid.
  const wrong = verifyAnchor(fx.tokenB64, fx.entryCount + 1, fx.headHash);
  checks.push(["wrong head: invalid", wrong.valid === false]);
  checks.push(["wrong head: does NOT cover head", wrong.messageImprintMatches === false]);
  checks.push(["wrong head: signature still authentic", wrong.signatureValid === true]);

  // 3) Tampered token bytes → signature fails.
  const buf = Buffer.from(fx.tokenB64, "base64"); buf[buf.length - 40] ^= 0xff;
  const tampered = verifyAnchor(buf.toString("base64"), fx.entryCount, fx.headHash);
  checks.push(["tampered token: invalid", tampered.valid === false]);
  checks.push(["tampered token: signature fails", tampered.signatureValid === false]);

  // 4) Garbage input → fail-closed (no throw).
  const garbage = verifyAnchor("not-a-real-token", fx.entryCount, fx.headHash);
  checks.push(["garbage token: invalid (fail-closed)", garbage.valid === false]);

  // 5) Dormant-by-default: with TSA_URL unset, the seam reports not-configured.
  checks.push(["dormant: isTsaConfigured() false", isTsaConfigured() === false]);
  checks.push(["dormant: status.configured false", tsaAnchorStatus().configured === false]);

  let pass = 0;
  for (const [name, ok] of checks) {
    console.log(`${ok ? "PASS" : "FAIL"}  ${name}`);
    if (ok) pass++;
  }
  console.log(`\n${pass}/${checks.length} checks passed`);
  if (pass !== checks.length) process.exit(1);
}
main().catch((e) => { console.error("SCRIPT ERROR", e); process.exit(1); });
