import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import evidence from "../../evidence/v2-onchain-usdc-payee-scan-20260509_13.json" assert { type: "json" };
import independentVerification from "../../evidence/v2-onchain-independent-verification.json" assert { type: "json" };
import screenshotReview from "../../evidence/x402-owner-screenshot-review-20260823.json" assert { type: "json" };

describe("owner-provided Base USDC log summary", () => {
  it("is explicitly on-chain-only and preserves the bounded external-payer totals", () => {
    expect(evidence).toMatchObject({
      schema: "vaultfire.x402.v2-onchain-payee-scan.v1",
      activation: "fail-closed-no-route-or-request-receipt-correlation",
      source: {
        lineCount: 173,
        sha256: "5458542ffb760d86ca1c0d2dc899324943531e27ec308b960093e5108dee5193",
      },
      externalPaymentCount: 19,
      externalAmountAtomic: "370000",
    });
    expect(evidence.notProven).toContain("V2 route or HTTP method");
    expect(evidence.externalPayments.map((payment) => [payment.payer, payment.count, payment.amountAtomic])).toEqual([
      ["0x7d188b4981bb4c8add7b89a1e8ee888cb8f29ae2", 1, "10000"],
      ["0x7e571e959cc7c75ccdd2eac24f8775ea2eaa2f09", 18, "360000"],
    ]);
  });

  it("keeps every transaction hash as an input for later independent RPC verification, not a receipt assertion", () => {
    const transactions = evidence.externalPayments.flatMap((payment) => payment.transactions);
    expect(transactions).toHaveLength(19);
    expect(new Set(transactions.map((transaction) => transaction.transactionHash)).size).toBe(19);
    expect(transactions.every((transaction) => /^0x[0-9a-f]{64}$/.test(transaction.transactionHash))).toBe(true);
    expect(createHash("sha256").update(JSON.stringify(transactions)).digest("hex")).toMatch(/^[a-f0-9]{64}$/);
    expect(readFileSync(resolve(import.meta.dirname, "../../docs/X402_RECEIPT_HARDENING.md"), "utf8"))
      .toContain("**not** V2 live-route, authorization, endpoint");
  });

  it("binds all selected transfers to successful independently verified Base receipts", () => {
    expect(independentVerification).toMatchObject({
      schema: "vaultfire.x402.v2-onchain-independent-verification.v1",
      network: "eip155:8453",
      chainId: 8453,
      requiredConfirmations: 64,
      transactionCount: 19,
      totalAmountAtomic: "370000",
      fullyApplicationCorrelatedCount: 0,
      activation: "fail-closed-no-route-or-request-receipt-correlation",
    });
    expect(independentVerification.records).toHaveLength(19);
    expect(
      independentVerification.records.every(
        (record) =>
          record.receiptStatus === "success" &&
          record.finalityPolicyResult === "pass" &&
          record.confirmationsAtVerification >= 64,
      ),
    ).toBe(true);
    expect(
      new Set(independentVerification.records.map((record) => record.transactionHash)),
    ).toEqual(
      new Set(
        evidence.externalPayments.flatMap((payment) =>
          payment.transactions.map((transaction) => transaction.transactionHash),
        ),
      ),
    );
    expect(independentVerification.notProven).toContain(
      "payment-response receipt",
    );
  });

  it("records that the playground screenshots do not provide receipt correlation", () => {
    expect(screenshotReview).toMatchObject({
      schema: "vaultfire.x402.owner-screenshot-review.v1",
      reviewedScreenshotCount: 20,
      visibleTransactionHashCount: 0,
      matchedReferenceTransactionCount: 0,
      visiblePaymentResponseReceiptCount: 0,
      visibleCoinbaseBazaarDiscoveryCount: 0,
      activation: "fail-closed-no-payment-or-response-correlation",
    });
  });
});
