import { existsSync, readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import compatibility from "../../compat/compatibility-discovery-v2-v3.json" assert { type: "json" };
import bazaar from "../../generated/coinbase-bazaar-v2.json" assert { type: "json" };
import registry from "../../generated/route-registry.json" assert { type: "json" };

const root = resolve(import.meta.dirname, "../../..");
const site = resolve(root, "repos/theloopbreaker-site");
const v3Store = resolve(site, "app/api/v3/x402/_lib/receipt-store.ts");
const legacyDuplicateStore = resolve(site, "app/api/x402/v3/_lib/receipt-store.ts");
function filesBelow(directory: string): string[] {
  if (!existsSync(directory)) return [];
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
    const path = resolve(directory, entry.name);
    return entry.isDirectory() ? filesBelow(path) : [path];
  });
}

describe("V3 x402 website integration remains isolated and fail-closed", () => {
  it("does not couple the isolated V3 receipt store into protected V2 x402 handlers", () => {
    expect(existsSync(v3Store)).toBe(true);
    expect(existsSync(legacyDuplicateStore)).toBe(true);
    const v2Sources = filesBelow(resolve(site, "app/api/x402")).filter((path) => path.endsWith(".ts") && !path.includes("/app/api/x402/v3/"));
    expect(v2Sources).not.toHaveLength(0);
    for (const source of v2Sources) expect(readFileSync(source, "utf8"), source).not.toMatch(/x402\/v3\/_lib\/receipt-store|v3\/_lib\/receipt-store/);
    const v3Sources = filesBelow(resolve(site, "app/api/v3")).filter((path) => path.endsWith(".ts"));
    for (const source of v3Sources) {
      expect(readFileSync(source, "utf8"), source).not.toMatch(/app\/api\/x402\/v3|api\/x402\/v3\/_lib\/receipt-store/);
    }
  });

  it("materializes only V3-only static/readiness handlers and no V3 payment candidate", () => {
    const v3 = registry.routes.filter((route) => route.version === "v3");
    expect(v3).toHaveLength(20);
    expect(v3.every((route) => route.free && route.contractStatus === "read-only" && route.bazaarEligibility === "not-priced")).toBe(true);
    const handlers = filesBelow(resolve(site, "app/api/v3")).filter((path) => path.endsWith("/route.ts"));
    expect(handlers).toHaveLength(20);
    expect(bazaar.resources.filter((resource) => resource.protocolVersion === "v3")).toHaveLength(0);
    expect(compatibility.operatingPolicy.v3DefaultState).toBe("fail-closed");
  });

  it("keeps the entire additive V3 namespace behind the exact website release gate", () => {
    const middleware = readFileSync(resolve(site, "middleware.ts"), "utf8");
    for (const text of ["'/api/v3/:path*'", "x402_release_gate_closed", "isAllowedV3ReleasePath", "isV3X402ReleaseEnabled"]) {
      expect(middleware).toContain(text);
    }
  });

  it("does not import V2 payment handlers, verifier code, or a V2 fallback from the additive V3 surface", () => {
    const v3Sources = filesBelow(resolve(site, "app/api/v3")).filter((path) => path.endsWith(".ts"));
    expect(v3Sources).not.toHaveLength(0);
    for (const source of v3Sources) {
      const text = readFileSync(source, "utf8");
      expect(text, source).not.toMatch(/verify-payment|actions\/_lib\/tx-encode|\/api\/x402\/trust\//);
      expect(text, source).not.toMatch(/0xfA15Ee28939B222B0448261A22156070f0A7813C/);
    }
  });

  it("keeps V3 production logs free of payment, authorization, nonce, body, and credential material", () => {
    const v3Sources = filesBelow(resolve(site, "app/api/v3")).filter((path) => path.endsWith(".ts"));
    for (const source of v3Sources) {
      const text = readFileSync(source, "utf8");
      expect(text, source).not.toMatch(/\bconsole\.(?:log|info|warn|error)|\blogger\./);
    }
    const store = readFileSync(v3Store, "utf8");
    expect(store).toContain("bindingDigestPrefix");
    expect(store).not.toMatch(/this\.audit\?\.\([^)]*(?:nonce|paymentId|authorizationId|binding:|observation:)/s);
  });
});
