import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { buildFinalReleaseRecord, scanReleaseFiles, validateFinalEvidence } from "../../scripts/lib/wp7-07-final-release.mjs";

function release() {
  return buildFinalReleaseRecord({
    appVersion: "0.0.0",
    browsers: [
      { brand: "Google Chrome", fullVersion: "150.0.7871.187" },
      { brand: "Microsoft Edge", fullVersion: "151.0.4129.59" },
    ],
    buildCommit: "a".repeat(40),
    frozenFromCommit: "b".repeat(40),
    recordedAt: "2026-08-04T06:00:00.000Z",
    windows: { arch: "x64", build: "26200.8875", displayVersion: "25H2" },
  });
}

test("TDD-WP7-REL-001 creates a browser-gate compatible first-version record", () => {
  const record = release();
  assert.equal(record.finalRelease, true);
  assert.equal(record.fixedPort, 43121);
  assert.deepEqual(record.deferredExternalTasks, ["TASK-WP7-03", "TASK-WP7-04"]);
  assert.deepEqual(record.browsers.map(({ brand }) => brand).sort(), ["Google Chrome", "Microsoft Edge"]);
});

test("TDD-WP7-SEC-001 rejects credential shapes and absolute user paths", () => {
  const root = mkdtempSync(join(tmpdir(), "dada-wp7-07-scan-"));
  mkdirSync(join(root, "logs"));
  writeFileSync(join(root, "logs", "diagnostic.txt"), "credential=key-abcdefghijklmnop C:\\Users\\person\\private.txt\n");
  const scan = scanReleaseFiles({ roots: [root] });
  assert.equal(scan.status, "failed");
  assert.deepEqual(new Set(scan.findings.map(({ rule }) => rule)), new Set(["absolute_user_path", "credential_shape"]));
});

test("TDD-WP7-REL-001 binds release and package hashes only after a zero-finding scan", () => {
  assert.deepEqual(validateFinalEvidence({
    packageManifest: { release_status: "first_version_internal", zip_sha256: "C".repeat(64) },
    release: release(),
    releaseSha256: "D".repeat(64),
    scan: { findings: [], status: "passed" },
  }), { release_sha256: "D".repeat(64), status: "passed", zip_sha256: "C".repeat(64) });
});
