import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "bun:test";

import { rootPath } from "./config";
import { readSub2RankConfig } from "./platform-infra-sub2rank-config";
import { readTemporalConfig } from "./platform-infra-temporal";
import { readDeclaredSecretValues } from "./secrets";
import { resolveSelfMediaDeliveryTarget } from "./selfmedia-config";
import { pikaoaDevelopmentRuntimeConfigRef, resolvePikaoaDevelopmentRuntimeTargetByConfigRef } from "./pikaoa-runtime";
import { webProbeScriptCommandGovernance } from "./hwlab-node/web-observe-scripts";
import {
  classifyWebProbeBrowserRuntimeAuthFailure,
  compactProductSmokeFailureEvidence,
  compactWebProbeScriptResult,
} from "./hwlab-node-web-probe-summary";
import {
  compactWebProbeProductSmokeProjection,
  parseWebProbeProductSmokeOptions,
  resolveWebProbeProductSmoke,
} from "./web-probe-product-smoke";
import { apiStateOperationsSmokeScript } from "./web-probe-apistate-smoke";
import {
  resolveTemporalProductSmoke,
  temporalAdminReadonlySmokeScript,
} from "./web-probe-temporal-smoke";

const fixture = {
  product: "selfmedia",
  target: "NC01",
  profile: "voice-algorithm",
  edition: "embedded-ai-chipmakers-20260714",
  algorithm: "cosyvoice3",
  runtime: null,
} as const;

test("SelfMedia 产品 smoke 完全由 owning YAML 解析，生产目标保持禁用", () => {
  const development = resolveSelfMediaDeliveryTarget("NC01");
  const production = resolveSelfMediaDeliveryTarget("NC01_PRODUCTION");
  assert.equal(development.webProbe.enabled, true);
  assert.equal(development.webProbe.origin.baseUrl, "https://media-dev.hwpod.com");
  assert.equal(development.webProbe.authentication.path, "/api/v1/auth/session");
  assert.equal(development.webProbe.smokeProfiles["voice-algorithm"]?.kind, "select-and-save");
  assert.equal(production.webProbe.enabled, false);
  assert.equal(production.gitops.credentialSecretName, "pac-gitea-selfmedia-nc01");
  assert.throws(() => resolveWebProbeProductSmoke({ ...fixture, target: "NC01_PRODUCTION" }), /enabled=false/u);
});

test("product-smoke 参数是单一 typed command，拒绝 URL 和未知参数", () => {
  assert.deepEqual(parseWebProbeProductSmokeOptions([
    "--product", fixture.product,
    "--target", fixture.target,
    "--profile", fixture.profile,
    "--edition", fixture.edition,
    "--algorithm", fixture.algorithm,
  ]), fixture);
  assert.throws(() => parseWebProbeProductSmokeOptions([
    "--product", fixture.product,
    "--target", fixture.target,
    "--edition", fixture.edition,
    "--algorithm", fixture.algorithm,
    "--url", "https://example.invalid",
  ]), /不支持参数 --url/u);
});

test("PikaOA admin-mvp 由 development runtime YAML 解析且不要求 SelfMedia 参数", () => {
  const options = parseWebProbeProductSmokeOptions([
    "--product", "pikaoa",
    "--target", "NC01",
    "--profile", "admin-mvp",
  ]);
  assert.deepEqual(options, { product: "pikaoa", target: "NC01", profile: "admin-mvp", edition: null, algorithm: null, runtime: null });
  const target = resolvePikaoaDevelopmentRuntimeTargetByConfigRef(pikaoaDevelopmentRuntimeConfigRef("NC01"));
  assert.equal(target.temporal.logicalNamespace, "unidesk");
  assert.equal(target.temporal.taskQueue, "pikaoa-dev-outbox");
  assert.equal(target.temporal.serviceRef.name, "temporal-frontend");
  assert.equal(target.webProbe.enabled, true);
  assert.equal(target.webProbe.authentication.mode, "ui-form-memory");
  assert.deepEqual(target.webProbe.smokeProfiles["admin-mvp"]?.routes.map((item) => item.path), ["/contracts", "/invoices", "/attachments"]);
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.contract.number, "CLI-2026-001");
  assert.deepEqual(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.attachments.names, ["pikaoa-contract-sample.pdf", "pikaoa-invoice-sample.pdf"]);
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.resourceReferences.filter.comboboxLabel, "伙伴");
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.resourceReferences.filter.queryParameter, "partnerId");
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.resourceReferences.detail.contract.pathPrefix, "/business-partners/");
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.resourceReferences.detail.invoice.label, "合同");
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.resourceReferences.detail.attachment.pathPrefix, "/contract-versions/");
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.invoice.layout.maxListTop, 220);
  assert.equal(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.invoice.layout.minListVisibleHeight, 700);
  assert.deepEqual(target.webProbe.smokeProfiles["admin-mvp"]?.businessAssertions?.invoice.layout.mobile.viewport, { width: 390, height: 844 });
  const resolved = resolveWebProbeProductSmoke(options);
  assert.equal(resolved.scriptOptions.viewport, "1920x1080");
  assert.equal(resolved.scriptOptions.scriptSource.path, "builtin:product-smoke/pikaoa/admin-mvp");
  assert.doesNotThrow(() => new Function(resolved.scriptOptions.scriptText.replace("export default ", "")));
  assert.match(resolved.scriptOptions.scriptText, /navigation\.click\(\)/u);
  assert.match(resolved.scriptOptions.scriptText, /verifyPdf/u);
  assert.match(resolved.scriptOptions.scriptText, /waitForEvent\("popup"/u);
  assert.match(resolved.scriptOptions.scriptText, /if \(!popup\.isClosed\(\)\) throw error/u);
  assert.match(resolved.scriptOptions.scriptText, /popupClosedBeforeBlob/u);
  assert.match(resolved.scriptOptions.scriptText, /popupCreated: true/u);
  assert.match(resolved.scriptOptions.scriptText, /response\.status\(\) === 200 && mediaType\.includes/u);
  assert.match(resolved.scriptOptions.scriptText, /documents\.attachments/u);
  assert.match(resolved.scriptOptions.scriptText, /invoiceShot = await screenshot\(layout\.screenshotName\)/u);
  assert.match(resolved.scriptOptions.scriptText, /captureInvoiceLayout/u);
  assert.match(resolved.scriptOptions.scriptText, /activeAttachmentCount/u);
  assert.match(resolved.scriptOptions.scriptText, /count < 1/u);
  assert.match(resolved.scriptOptions.scriptText, /verifyPartnerFilter/u);
  assert.match(resolved.scriptOptions.scriptText, /verifyDetailResourceLink/u);
  assert.match(resolved.scriptOptions.scriptText, /performance\.getEntriesByType\("resource"\)/u);
  assert.match(resolved.scriptOptions.scriptText, /if \(apiUrl === null\) throw new Error/u);
  assert.match(resolved.scriptOptions.scriptText, /selectedDisplayIsName/u);
  assert.match(resolved.scriptOptions.scriptText, /urlAndApiIdentityRemainId/u);
  assert.doesNotMatch(resolved.scriptOptions.scriptText, /page\.goto/u);
  assert.doesNotMatch(resolved.commandLabel, /https?:\/\//u);
  assert.throws(() => resolveWebProbeProductSmoke({ ...options, edition: "not-used" }), /不接受 --edition/u);
});

test("PikaOA release smoke 由 release runtime YAML 解析", () => {
  const resolved = resolveWebProbeProductSmoke({ product: "pikaoa", target: "NC01", profile: "admin-mvp", edition: null, algorithm: null, runtime: "release" });
  assert.equal(resolved.target.webProbe.origin.baseUrl, "https://oa.hwpod.com");
  assert.equal(resolved.target.temporal.taskQueue, "pikaoa-outbox");
  assert.match(resolved.commandLabel, /--runtime release/u);
  assert.match(resolved.configRef, /releaseRuntime/u);
});

test("PikaOA native smoke 只从 development owning YAML 解析 local origin", () => {
  const resolved = resolveWebProbeProductSmoke({ product: "pikaoa", target: "NC01", profile: "admin-mvp", edition: null, algorithm: null, runtime: "native" });
  assert.equal(resolved.target.native.web.endpoint, "http://127.0.0.1:4173");
  assert.equal(resolved.scriptOptions.url, "http://127.0.0.1:4173");
  assert.equal(resolved.scriptOptions.originMode, "custom-url");
  assert.equal(resolved.scriptOptions.browserProxyMode, "direct");
  assert.match(resolved.scriptOptions.originConfigPath, /developmentRuntime\.targets\.NC01\.native\.webProbe\.origin/u);
  assert.match(resolved.commandLabel, /--runtime native/u);
  assert.throws(() => resolveWebProbeProductSmoke({ product: "pikaoa", target: "NC01", profile: "admin-mvp", edition: null, algorithm: null, runtime: "local" }), /development、release 或 native/u);
});

test("ApiState product-smoke 只需要产品、目标和 YAML profile", () => {
  assert.deepEqual(parseWebProbeProductSmokeOptions([
    "--product", "apistate",
    "--target", "NC01",
    "--profile", "operations",
  ]), {
    product: "apistate",
    target: "NC01",
    profile: "operations",
    edition: null,
    algorithm: null,
    runtime: null,
  });
  const config = readSub2RankConfig();
  const profile = config.webProbe.smokeProfiles.operations;
  assert.ok(profile);
  assert.equal(config.webProbe.authentication.path, "/api/login");
  assert.equal(config.webProbe.authentication.passwordTargetKey, "APISTATE_WEB_PASSWORD");
  assert.deepEqual(profile.pages.map((item) => item.id), ["scores", "ranking", "lottery"]);
  const script = apiStateOperationsSmokeScript("operations", profile, "fixture#operations");
  assert.doesNotThrow(() => new Function(script.replace("export default ", "")));
  assert.doesNotMatch(script, /\.click\(/u);
  assert.match(script, /mutatingRequests/u);
  assert.match(script, /screenshot\(item\.screenshotName\)/u);
});

test("Temporal Basic Auth smoke 只从 owning YAML 和统一 Secret 声明解析", () => {
  const parsed = parseWebProbeProductSmokeOptions([
    "--product", "temporal",
    "--target", "NC01",
    "--profile", "admin-readonly",
  ]);
  assert.deepEqual(parsed, {
    product: "temporal",
    target: "NC01",
    profile: "admin-readonly",
    edition: null,
    algorithm: null,
    runtime: null,
  });
  const temporal = readTemporalConfig();
  assert.equal(temporal.webProbe.authentication.mode, "basic-auth");
  assert.equal(temporal.webProbe.authentication.path, "/namespaces/unidesk/workflows");
  assert.equal(temporal.webProbe.authentication.credentials.configRef, "config/secrets-distribution.yaml");
  assert.equal(temporal.webProbe.authentication.credentials.secretName, "temporal-web-admin");
  assert.equal(temporal.webProbe.authentication.credentials.passwordTargetKey, "password");
  const resolved = resolveTemporalProductSmoke({ target: parsed.target, profile: parsed.profile });
  assert.equal(resolved.scriptOptions.url, "https://temporal.hwpod.com");
  assert.equal(resolved.scriptOptions.viewport, "1920x1080");
  assert.equal(resolved.profile.path, "/namespaces/unidesk/workflows");
  assert.equal(resolved.scriptOptions.scriptSource.path, "builtin:product-smoke/temporal/admin-readonly");
  assert.doesNotMatch(resolved.commandLabel, /https?:\/\//u);
  const script = temporalAdminReadonlySmokeScript(resolved.profileName, resolved.profile, resolved.configRef, temporal.publicExposure.healthPath);
  assert.doesNotThrow(() => new Function(script.replace("export default ", "")));
  assert.doesNotMatch(script, /\.click\(|\.fill\(|\.press\(/u);
  assert.match(script, /mutation: false/u);
  assert.match(script, /valuesRedacted: true/u);
  assert.match(script, /failure\.includes\("net::ERR_ABORTED"\)/u);
  assert.match(script, /health\.status !== 200/u);
});

test("managed runner 通过 BrowserContext httpCredentials 泛化 Basic Auth", () => {
  const runner = readFileSync(rootPath("scripts/src/hwlab-node-web-probe-runner-source.ts"), "utf8");
  assert.match(runner, /authProfile\.mode === "basic-auth"/u);
  assert.match(runner, /httpCredentials: \{ username, password, send: "always" \}/u);
  assert.match(runner, /authenticateWithBasicAuth/u);
  assert.match(runner, /unauthenticatedResponse\.status\(\) !== 401/u);
  assert.match(runner, /valuesRedacted: true/u);
});

test("Temporal 统一 Secret 摘要不包含凭据值", () => {
  const temporal = readTemporalConfig();
  const credentials = temporal.webProbe.authentication.credentials;
  const material = readDeclaredSecretValues({
    configPath: credentials.configRef,
    targetId: credentials.targetId,
    secretName: credentials.secretName,
    targetKeys: [credentials.passwordTargetKey],
  });
  assert.equal(material.summary.valuesPrinted, false);
  assert.equal(material.summary.keys[0]?.present, true);
  assert.match(material.summary.fingerprint, /^sha256:/u);
  const publicText = JSON.stringify(material.summary);
  for (const value of Object.values(material.values)) assert.equal(publicText.includes(JSON.stringify(value)), false);
});

test("生成脚本可解析并复用 managed web-probe，无临时脚本警告", () => {
  const resolved = resolveWebProbeProductSmoke(fixture);
  assert.equal(resolved.scriptOptions.action, "script");
  assert.equal(resolved.scriptOptions.scriptSource.kind, "generated");
  assert.equal(resolved.scriptOptions.scriptSource.path, "builtin:product-smoke/selfmedia/voice-algorithm");
  assert.equal(resolved.scriptOptions.suppressAdHocWarning, true);
  assert.doesNotThrow(() => new Function(resolved.scriptOptions.scriptText.replace("export default ", "")));
  assert.match(resolved.scriptOptions.scriptText, /reloadStable/u);
  assert.match(resolved.scriptOptions.scriptText, /reportSha256/u);
  assert.doesNotMatch(resolved.commandLabel, /https?:\/\//u);
  const governance = webProbeScriptCommandGovernance(resolved.scriptOptions);
  assert.deepEqual(governance.warnings, []);
  assert.equal(governance.commandPromotionHint.repoOwnedTypedCommand, true);
});

test("受控 Secret 读取只公开 sourceRef、presence 与 fingerprint", () => {
  const target = resolveSelfMediaDeliveryTarget("NC01");
  const credentials = target.webProbe.authentication.credentials;
  const material = readDeclaredSecretValues({
    configPath: credentials.configRef,
    targetId: credentials.targetId,
    secretName: credentials.secretName,
    targetKeys: [credentials.usernameTargetKey, credentials.passwordTargetKey],
  });
  assert.equal(material.summary.valuesPrinted, false);
  assert.ok(material.summary.keys.every((item) => item.present));
  assert.match(material.summary.fingerprint, /^sha256:/u);
  const publicText = JSON.stringify(material.summary);
  for (const value of Object.values(material.values)) assert.equal(publicText.includes(JSON.stringify(value)), false);
});

test("managed runner 的登录路径、字段和 cookie 都来自显式认证 profile", () => {
  const runner = readFileSync(rootPath("scripts/src/hwlab-node-web-probe-runner-source.ts"), "utf8");
  const managed = readFileSync(rootPath("scripts/src/hwlab-node/web-observe-scripts.ts"), "utf8");
  assert.match(runner, /new URL\(authProfile\.loginPath, baseUrl\)/u);
  assert.match(runner, /\[authProfile\.usernameField\]/u);
  assert.match(runner, /\[authProfile\.passwordField\]/u);
  assert.match(runner, /authProfile\.cookieNames\.some/u);
  assert.match(runner, /UNIDESK_WEB_PROBE_BROWSER_STAGE/u);
  assert.match(managed, /UNIDESK_WEB_PROBE_AUTH_PROFILE/u);
  assert.match(managed, /runManagedNodeWebProbeScript/u);
  assert.match(runner, /ui-form-memory/u);
  assert.match(runner, /page = await context\.newPage\(\)/u);
});

test("首次 UI 导航关闭且未发出认证请求时分类为浏览器运行时 blocker", () => {
  const report = {
    ok: false,
    status: "blocked",
    error: "auth-login-failed",
    errorMessage: "auth-login-failed",
    reportPath: ".state/web-probe-script/run.fixture/web-probe-script-report.json",
    reportSha256: `sha256:${"a".repeat(64)}`,
    auth: {
      ok: false,
      method: "ui-form-memory",
      status: 0,
      usernamePresent: true,
      attempts: [{ method: "ui-form-memory", response: null, finalPath: null }],
      errorSummary: { message: "page.goto: Target page, context or browser has been closed" },
      valuesRedacted: true,
    },
    script: { ok: false, steps: [] },
    steps: [],
  };
  const blocker = classifyWebProbeBrowserRuntimeAuthFailure(report);
  assert.deepEqual(blocker, {
    code: "browser-runtime-closed",
    failureKind: "browser-runtime-blocker",
    credentialResolved: true,
    requestReached: false,
    apiResponseReached: false,
    errorSummary: {
      message: "page.goto: Target page, context or browser has been closed",
      status: 0,
      response: null,
      stepCount: 0,
      valuesRedacted: true,
    },
    valuesRedacted: true,
  });
  const compact = compactWebProbeScriptResult(report);
  assert.equal(compact?.failureKind, "browser-runtime-blocker");
  assert.equal(compact?.error, "browser-runtime-closed");
  assert.deepEqual(compact?.issueEvidence, {
    ok: false,
    status: "blocked",
    credentialResolved: true,
    requestReached: false,
    apiResponseReached: false,
    errorSummary: {
      message: "page.goto: Target page, context or browser has been closed",
      status: 0,
      response: null,
      stepCount: 0,
      valuesRedacted: true,
    },
    degradedReason: "browser-runtime-closed",
    failureKind: "browser-runtime-blocker",
    failedCondition: "page.goto: Target page, context or browser has been closed",
    nextAction: null,
    baseUrl: null,
    finalUrl: null,
    lastUrl: null,
    scriptSha256: null,
    runDir: null,
    reportPath: ".state/web-probe-script/run.fixture/web-probe-script-report.json",
    reportSha256: `sha256:${"a".repeat(64)}`,
    result: null,
    apiMatrix: null,
    lastStep: null,
    steps: [],
    lastScreenshot: null,
    screenshots: [],
    valuesRedacted: true,
  });
});

test("首次 UI 导航资源耗尽不误报目标认证失败", () => {
  const report = {
    ok: false,
    status: "blocked",
    error: "auth-login-failed",
    errorMessage: "auth-login-failed",
    auth: {
      ok: false,
      method: "ui-form-memory",
      status: 0,
      usernamePresent: true,
      attempts: [{ method: "ui-form-memory", response: null, finalPath: "blank" }],
      errorSummary: { message: "page.goto: net::ERR_INSUFFICIENT_RESOURCES at https://example.test/login", finalPath: "blank" },
    },
    script: { ok: false, steps: [] },
    steps: [],
  };
  const blocker = classifyWebProbeBrowserRuntimeAuthFailure(report);
  assert.equal(blocker?.code, "browser-runtime-resource-exhausted");
  assert.equal(blocker?.failureKind, "browser-runtime-blocker");
  assert.equal(blocker?.credentialResolved, true);
  assert.equal(blocker?.requestReached, false);
  assert.equal(blocker?.apiResponseReached, false);

  const probe = compactWebProbeScriptResult(report);
  assert.equal(probe?.error, "browser-runtime-resource-exhausted");
  assert.equal(probe?.failureKind, "browser-runtime-blocker");
  const projection = compactWebProbeProductSmokeProjection({
    ok: false,
    status: "blocked",
    node: "NC01",
    lane: "v03",
    probe,
  });
  assert.equal(projection.degradedReason, "browser-runtime-resource-exhausted");
  assert.equal(projection.failureKind, "browser-runtime-blocker");
  assert.deepEqual(projection.reachability, {
    credentialResolved: true,
    requestReached: false,
    apiResponseReached: false,
    errorSummary: {
      message: "page.goto: net::ERR_INSUFFICIENT_RESOURCES at https://example.test/login",
      status: 0,
      response: null,
      stepCount: 0,
      valuesRedacted: true,
    },
  });
});

test("product-smoke 默认机器投影有界且保留一次判定所需字段", () => {
  const reportSha256 = `sha256:${"a".repeat(64)}`;
  const projection = compactWebProbeProductSmokeProjection({
    ok: false,
    status: "blocked",
    command: "web-probe product-smoke --product fixture --target NC01 --profile admin",
    node: "NC01",
    lane: "v03",
    url: "https://fixture.example.test",
    degradedReason: "browser-runtime-resource-exhausted",
    failureKind: "browser-runtime-blocker",
    issueEvidence: {
      credentialResolved: true,
      requestReached: false,
      apiResponseReached: false,
      failedCondition: "page.goto: net::ERR_INSUFFICIENT_RESOURCES",
      errorSummary: { message: "page.goto: net::ERR_INSUFFICIENT_RESOURCES" },
      result: { noisy: "x".repeat(30_000) },
    },
    probe: {
      reportPath: ".state/web-probe-script/run.fixture/web-probe-script-report.json",
      reportSha256,
      artifacts: { items: [{ kind: "json", path: ".state/report.json", sha256: reportSha256, byteCount: 30_000 }] },
      noisy: "x".repeat(30_000),
    },
    result: { stdoutTail: "x".repeat(30_000) },
    productSmoke: { product: "fixture", target: "NC01", profile: "admin", valuesPrinted: false },
  });
  assert.equal(projection.failureKind, "browser-runtime-blocker");
  assert.deepEqual(projection.reachability, {
    credentialResolved: true,
    requestReached: false,
    apiResponseReached: false,
    errorSummary: { message: "page.goto: net::ERR_INSUFFICIENT_RESOURCES" },
  });
  assert.match(String((projection.next as Record<string, unknown>).report), /web-probe artifact inspect/u);
  assert.ok(Buffer.byteLength(JSON.stringify(projection)) < 10_240);
});

test("product-smoke 接受显式完整披露标志且不把它当产品参数", () => {
  const parsed = parseWebProbeProductSmokeOptions([
    "--product", "pikaoa", "--target", "NC01", "--profile", "admin-mvp", "--runtime", "development", "--full", "--raw",
  ]);
  assert.equal(parsed.product, "pikaoa");
  assert.equal(parsed.runtime, "development");
});

test("真实认证响应或已发出的登录请求不降级为浏览器运行时 blocker", () => {
  const base = {
    auth: {
      method: "ui-form-memory",
      status: 0,
      usernamePresent: true,
      attempts: [{ response: null }],
      errorSummary: { message: "page.goto: Target page, context or browser has been closed" },
    },
    script: { steps: [] },
  };
  assert.equal(classifyWebProbeBrowserRuntimeAuthFailure({
    ...base,
    auth: { ...base.auth, status: 401, attempts: [{ response: { status: 401 } }] },
  }), null);
  assert.equal(classifyWebProbeBrowserRuntimeAuthFailure({
    ...base,
    auth: { ...base.auth, requestReached: true },
  }), null);
});

test("product-smoke PDF 失败证据优先投影判定字段和工件哈希", () => {
  const reportSha256 = `sha256:${"a".repeat(64)}`;
  const screenshotSha256 = `sha256:${"b".repeat(64)}`;
  const evidence = compactProductSmokeFailureEvidence({
    ok: false,
    errorMessage: `发票 PDF 响应无效：${JSON.stringify({
      documentType: "发票",
      path: "/api/reports/very/long/path/that/previously/occupied/the/compact/preview",
      status: 503,
      mediaType: "text/html; charset=utf-8",
      popupCreated: true,
      popupProtocol: "about:",
      popupClosedBeforeBlob: true,
      ok: false,
    })}`,
    artifacts: { items: [{ kind: "screenshot", path: ".state/web-probe-script/run.fixture/failure.png", sha256: screenshotSha256 }] },
  }, ".state/web-probe-script/run.fixture/web-probe-script-report.json", reportSha256);
  assert.deepEqual(evidence, {
    kind: "pdf-verification",
    status: 503,
    mediaType: "text/html; charset=utf-8",
    popupCreated: true,
    popupProtocol: "about:",
    popupClosedBeforeBlob: true,
    documentType: "发票",
    path: "/api/reports/very/long/path/that/previously/occupied/the/compact/preview",
    reportPath: ".state/web-probe-script/run.fixture/web-probe-script-report.json",
    reportSha256,
    screenshotPath: ".state/web-probe-script/run.fixture/failure.png",
    screenshotSha256,
    valuesRedacted: true,
  });
});

test("成功 product-smoke 不投影 PDF 失败证据", () => {
  const evidence = compactProductSmokeFailureEvidence({
    ok: true,
    script: {
      result: {
        report: {
          items: [{
            documentType: "发票",
            status: 200,
            mediaType: "application/pdf",
            popupCreated: true,
            popupProtocol: "blob:",
            popupClosedBeforeBlob: false,
            path: "/api/reports/invoice.pdf",
            ok: true,
          }],
        },
      },
    },
  });
  assert.equal(evidence, null);
});
