// Emissar Receipt v0.1 reference demo (https://emissar.ai/specs/receipt/v0.1, Appendix B).
//
//   node receipt-demo.mjs          human-readable run
//   node receipt-demo.mjs --json   example objects as JSON (read by validate.py)
//
// Tested with Node v24.13.0. No dependencies: WebCrypto only.
// Party keys are the PUBLIC TEST KEYS from RFC 7515 Appendix A.3 (ES256) and RFC 8037 Appendix A.1 (Ed25519),
// so digests are reproducible. Never use them for anything real. Salts are derived from fixed labels for the
// same reason; section 6.4 requires 128-bit random salts in real use. All names, tasks and amounts are illustrative.

// RFC 8785 (JCS), base64url and the JWS algorithm table, the same code Emissar signs its own Agent Cards with.
// JSON.stringify already serializes strings and numbers the way RFC 8785 section 3.2.2 requires (ECMAScript rules),
// and the default sort compares UTF-16 code units (section 3.2.3).
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
const MAX_DEPTH = 128;
function canonicalize(v, depth = 0) {
  if (depth > MAX_DEPTH) throw new Error(`nesting is deeper than ${MAX_DEPTH} levels`);
  if (v === null) return "null";
  switch (typeof v) {
    case "boolean":
      return v ? "true" : "false";
    case "number":
      if (!Number.isFinite(v)) throw new Error("a number is not finite");
      return JSON.stringify(v); // -0 serializes as 0, as RFC 8785 requires
    case "string":
      if (LONE_SURROGATE.test(v)) throw new Error("a string contains an unpaired surrogate");
      return JSON.stringify(v);
    case "object": {
      if (Array.isArray(v)) return `[${v.map((x) => canonicalize(x, depth + 1)).join(",")}]`;
      const keys = Object.keys(v).filter((k) => v[k] !== undefined).sort();
      return `{${keys.map((k) => {
        if (LONE_SURROGATE.test(k)) throw new Error("a key contains an unpaired surrogate");
        return `${JSON.stringify(k)}:${canonicalize(v[k], depth + 1)}`;
      }).join(",")}}`;
    }
    default:
      throw new Error(`${typeof v} has no JSON form`);
  }
}
function b64urlToBytes(s) {
  if (!/^[A-Za-z0-9_-]*$/.test(s)) throw new Error("not base64url");
  const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4));
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}
function bytesToB64url(b) {
  let bin = "";
  for (const x of b) bin += String.fromCharCode(x);
  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
const ED25519 = { kty: "OKP", crv: "Ed25519", imp: { name: "Ed25519" }, ver: { name: "Ed25519" }, sigLen: 64 };
const ALGS = {
  ES256: { kty: "EC", crv: "P-256", imp: { name: "ECDSA", namedCurve: "P-256" }, ver: { name: "ECDSA", hash: "SHA-256" }, sigLen: 64 },
  ES384: { kty: "EC", crv: "P-384", imp: { name: "ECDSA", namedCurve: "P-384" }, ver: { name: "ECDSA", hash: "SHA-384" }, sigLen: 96 },
  RS256: { kty: "RSA", imp: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, ver: { name: "RSASSA-PKCS1-v1_5" } },
  PS256: { kty: "RSA", imp: { name: "RSA-PSS", hash: "SHA-256" }, ver: { name: "RSA-PSS", saltLength: 32 } },
  EdDSA: ED25519,
  Ed25519: ED25519, // fully specified name from RFC 9864
};

const { subtle } = globalThis.crypto;
const EXT = "https://emissar.ai/ext/receipt/v1";
const TYP = "emissar-receipt+json";
const JSON_MODE = process.argv.includes("--json");
const out = (...a) => { if (!JSON_MODE) console.log(...a); };
const enc = (s) => new TextEncoder().encode(s);
const eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
const concat = (...parts) => {
  const o = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
  let i = 0;
  for (const p of parts) { o.set(p, i); i += p.length; }
  return o;
};
let failures = 0;
const expect = (label, ok, detail = "") => {
  if (!ok) failures++;
  out(`  ${ok ? "PASS" : "FAIL"}  ${label}${detail ? `  (${detail})` : ""}`);
};

// ---------------------------------------------------------------------------------------------
// Section 6: canonical bytes, digests (RFC 6920 ni URIs), commitments, key thumbprints (RFC 7638)

const HASH = { "sha-256": ["SHA-256", 32], "sha-384": ["SHA-384", 48], "sha-512": ["SHA-512", 64] };
const H = async (alg, bytes) => {
  if (!HASH[alg]) throw new Error(`digest algorithm ${alg} is not allowed`);
  return new Uint8Array(await subtle.digest(HASH[alg][0], bytes));
};
const toNi = (alg, bytes) => `ni:///${alg};${bytesToB64url(bytes)}`;
function fromNi(s) {
  const m = /^ni:\/\/\/(sha-256|sha-384|sha-512);([A-Za-z0-9_-]+)$/.exec(String(s));
  if (!m) throw new Error(`not an allowed ni digest: ${s}`);
  const bytes = b64urlToBytes(m[2]);
  if (bytes.length !== HASH[m[1]][1]) throw new Error(`wrong digest length in ${s}`);
  return { alg: m[1], bytes };
}
const jcs = (v) => enc(canonicalize(v));
const digestOf = async (alg, v) => toNi(alg, await H(alg, jcs(v)));
const commit = (alg, salt, value) => digestOf(alg, { salt, value });
const receiptDigest = (receipt) => digestOf(receipt.digestAlg, receipt);

const TP_MEMBERS = { EC: ["crv", "kty", "x", "y"], OKP: ["crv", "kty", "x"], RSA: ["e", "kty", "n"] };
async function thumbprint(jwk) {
  const members = TP_MEMBERS[jwk.kty];
  if (!members) throw new Error(`no thumbprint rule for kty ${jwk.kty}`);
  return bytesToB64url(await H("sha-256", jcs(Object.fromEntries(members.map((k) => [k, jwk[k]])))));
}

// Section 6.5: projections of A2A v1.0 objects. Metadata and extension lists are excluded; raw bytes are hashed.
function b64AnyToBytes(s) {
  return b64urlToBytes(s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""));
}
async function partProjection(p, alg) {
  const kinds = ["text", "raw", "url", "data"].filter((k) => k in p);
  if (kinds.length !== 1) throw new Error("a Part must carry exactly one of text, raw, url, data");
  const o = {};
  if (kinds[0] === "raw") o.rawDigest = toNi(alg, await H(alg, b64AnyToBytes(p.raw)));
  else o[kinds[0]] = p[kinds[0]];
  if (p.mediaType) o.mediaType = p.mediaType;
  if (p.filename) o.filename = p.filename;
  return o;
}
const partsOf = (parts, alg) => Promise.all(parts.map((p) => partProjection(p, alg)));
async function messageProjection(m, alg) {
  const o = { messageId: m.messageId, role: m.role, parts: await partsOf(m.parts, alg) };
  if (m.referenceTaskIds?.length) o.referenceTaskIds = m.referenceTaskIds;
  return o;
}
async function artifactProjection(a, alg) {
  const o = { artifactId: a.artifactId, parts: await partsOf(a.parts, alg) };
  if (a.name) o.name = a.name;
  if (a.description) o.description = a.description;
  return o;
}
const isReceiptArtifact = (a) => Array.isArray(a.extensions) && a.extensions.includes(EXT);

// Section 5: build the receipt payload and the openings (salts) from the server's view of the task.
async function buildReceipt({ receiptId, endpoint, task, clientMessages, parties, mandates, payments, acceptedAt, issuedAt, windowSeconds, salt, alg = "sha-256" }) {
  const openings = { receiptId, request: {}, outcome: { artifacts: {} } };
  const request = { messages: [] };
  for (const m of clientMessages) {
    const s = await salt(`request/${m.messageId}`);
    openings.request[m.messageId] = s;
    request.messages.push({ messageId: m.messageId, digest: await commit(alg, s, await messageProjection(m, alg)) });
  }
  const outcome = { state: task.status.state, artifacts: [] };
  if (task.status.message) {
    const s = await salt(`status/${task.status.message.messageId}`);
    openings.outcome.statusMessage = s;
    outcome.statusMessage = { messageId: task.status.message.messageId, digest: await commit(alg, s, await messageProjection(task.status.message, alg)) };
  }
  for (const a of (task.artifacts ?? []).filter((x) => !isReceiptArtifact(x))) {
    const s = await salt(`artifact/${a.artifactId}`);
    openings.outcome.artifacts[a.artifactId] = s;
    outcome.artifacts.push({ artifactId: a.artifactId, digest: await commit(alg, s, await artifactProjection(a, alg)) });
  }
  const countersignBy = new Date(Date.parse(issuedAt) + windowSeconds * 1000).toISOString();
  const receipt = { // member order is for readability only; RFC 8785 sorts keys before hashing and signing
    version: "0.1",
    receiptId,
    digestAlg: alg,
    task: { endpoint, taskId: task.id, contextId: task.contextId },
    parties,
    ...(mandates?.length ? { mandates } : {}),
    request,
    outcome,
    ...(payments?.length ? { payments } : {}),
    timestamps: { acceptedAt, terminalAt: new Date(Date.parse(task.status.timestamp)).toISOString(), issuedAt, countersignBy },
  };
  return { receipt, openings };
}

// ---------------------------------------------------------------------------------------------
// Sections 7 and 8: detached-payload JWS (RFC 7515 general JSON serialization) and per-key hash chains

async function loadSigner(alg, kid, privateJwk) {
  const privateKey = await subtle.importKey("jwk", privateJwk, ALGS[alg].imp, false, ["sign"]);
  const { d: _d, ...pub } = privateJwk;
  const jkt = await thumbprint(pub);
  return { alg, kid, privateKey, publicJwk: { ...pub, kid, alg, use: "sig" }, jkt, chain: { seq: 0, head: await genesisHead("sha-256", jkt) } };
}
// Section 8.1: h(0) binds a chain to its signing key; h(n) = H(h(n-1) || receipt digest n).
const genesisHead = async (alg, jkt) => toNi(alg, await H(alg, enc(jkt)));
const decodeHeader = (p) => JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(b64urlToBytes(p)));

async function nextHead(prevHeadNi, digestNi) {
  const d = fromNi(digestNi);
  const prev = fromNi(prevHeadNi);
  if (prev.alg !== d.alg) throw new Error("a chain uses one digest algorithm");
  return toNi(d.alg, await H(d.alg, concat(prev.bytes, d.bytes)));
}

async function signAs(doc, role, signer, signedAt) {
  const ext = { role, seq: signer.chain.seq + 1, prev: signer.chain.head, signedAt };
  const header = { alg: signer.alg, kid: signer.kid, typ: TYP, crit: [EXT], [EXT]: ext };
  const protectedB64 = bytesToB64url(enc(JSON.stringify(header)));
  const input = enc(`${protectedB64}.${bytesToB64url(jcs(doc.receipt))}`);
  const sig = new Uint8Array(await subtle.sign(ALGS[signer.alg].ver, signer.privateKey, input));
  doc.signatures.push({ protected: protectedB64, signature: bytesToB64url(sig) });
  signer.chain = { seq: ext.seq, head: await nextHead(signer.chain.head, await receiptDigest(doc.receipt)) };
}

async function signDetached(obj, signer, typ) {
  const protectedB64 = bytesToB64url(enc(JSON.stringify({ alg: signer.alg, kid: signer.kid, typ })));
  const sig = await subtle.sign(ALGS[signer.alg].ver, signer.privateKey, enc(`${protectedB64}.${bytesToB64url(jcs(obj))}`));
  return { protected: protectedB64, signature: bytesToB64url(new Uint8Array(sig)) };
}
async function verifyDetached(obj, s, jwk, typ) {
  const h = decodeHeader(s.protected);
  if (h.typ !== typ || !ALGS[h.alg] || h.kid !== jwk.kid) return false;
  const { d: _d, ...pub } = jwk;
  const key = await subtle.importKey("jwk", pub, ALGS[h.alg].imp, false, ["verify"]);
  return subtle.verify(ALGS[h.alg].ver, key, b64urlToBytes(s.signature), enc(`${s.protected}.${bytesToB64url(jcs(obj))}`));
}

// ---------------------------------------------------------------------------------------------
// Section 12: verification algorithm (steps 1-9; chain, anchor and opening checks are separate functions)

const TRUST = { algs: ["ES256", "ES384", "Ed25519"], skewSeconds: 300, keys: {} };

async function verifyReceipt(doc, trust, { requireCountersigned = false } = {}) {
  const r = { valid: false, countersigned: false, digest: null, signers: {}, errors: [] };
  const rc = doc?.receipt;
  if (!rc || rc.version !== "0.1") { r.errors.push("missing receipt or unsupported version"); return r; }
  let payloadB64;
  try {
    payloadB64 = bytesToB64url(jcs(rc));
    r.digest = await receiptDigest(rc);
  } catch (e) {
    r.errors.push(`no canonical form or bad digestAlg: ${e.message}`);
    return r;
  }
  for (const [i, s] of (Array.isArray(doc.signatures) ? doc.signatures : []).entries()) {
    let h;
    try { h = decodeHeader(s.protected); } catch { r.errors.push(`signature ${i}: protected header is not base64url JSON`); continue; }
    const ext = h[EXT];
    if (h.typ !== TYP || !Array.isArray(h.crit) || h.crit.length !== 1 || h.crit[0] !== EXT || typeof ext !== "object" || ext === null) { r.errors.push(`signature ${i}: typ, crit or receipt header parameter missing or wrong`); continue; }
    if (!trust.algs.includes(h.alg) || !ALGS[h.alg]) { r.errors.push(`signature ${i}: alg ${h.alg} not accepted`); continue; }
    const role = ext.role;
    if (role !== "server" && role !== "client") { r.errors.push(`signature ${i}: unknown role`); continue; }
    if (r.signers[role]) { r.errors.push(`signature ${i}: second ${role} signature`); continue; }
    const party = rc.parties?.[role];
    if (!party || h.kid !== party.signingKey?.kid) { r.errors.push(`${role} signature: kid does not match parties.${role}.signingKey.kid`); continue; }
    const jwk = trust.keys[h.kid];
    if (!jwk) { r.errors.push(`${role} signature: no trusted key for kid ${h.kid}`); continue; }
    if ((await thumbprint(jwk)) !== party.signingKey.jkt) { r.errors.push(`${role} signature: key thumbprint does not match parties.${role}.signingKey.jkt`); continue; }
    const { d: _d, ...pub } = jwk;
    const key = await subtle.importKey("jwk", pub, ALGS[h.alg].imp, false, ["verify"]);
    const ok = await subtle.verify(ALGS[h.alg].ver, key, b64urlToBytes(s.signature), enc(`${s.protected}.${payloadB64}`));
    if (!ok) { r.errors.push(`${role} signature does not verify over the canonical receipt`); continue; }
    r.signers[role] = { kid: h.kid, seq: ext.seq, prev: ext.prev ?? null, signedAt: ext.signedAt };
  }
  const t = rc.timestamps ?? {};
  const ms = (x) => Date.parse(x);
  const skew = trust.skewSeconds * 1000;
  if (!(ms(t.acceptedAt) <= ms(t.terminalAt) && ms(t.terminalAt) <= ms(t.issuedAt) && ms(t.issuedAt) < ms(t.countersignBy))) r.errors.push("timestamps out of order");
  const sv = r.signers.server;
  const cl = r.signers.client;
  if (!sv) r.errors.push("no valid server (issuer) signature");
  if (sv && ms(sv.signedAt) + skew < ms(t.issuedAt)) r.errors.push("server signedAt is before issuedAt");
  if (sv && cl && ms(cl.signedAt) + skew < ms(sv.signedAt)) r.errors.push("client signedAt is before server signedAt");
  if (cl && ms(cl.signedAt) > ms(t.countersignBy) + skew) r.errors.push("client countersigned after countersignBy");
  r.valid = r.errors.length === 0;
  r.countersigned = r.valid && !!cl;
  if (requireCountersigned && r.valid && !cl) { r.valid = false; r.errors.push("policy requires both signatures; the client signature is missing"); }
  return r;
}

// Section 8.3: verify one key's chain across consecutive receipts it signed, in seq order.
async function verifyChain(docs, kid) {
  let head = null;
  let seq = null;
  for (const doc of docs) {
    const s = doc.signatures.find((x) => decodeHeader(x.protected).kid === kid);
    if (!s) return { ok: false, error: `receipt ${doc.receipt.receiptId} has no signature by ${kid}` };
    const ext = decodeHeader(s.protected)[EXT];
    if (seq === null && ext.seq === 1) {
      const party = Object.values(doc.receipt.parties).find((p) => p.signingKey.kid === kid);
      if (ext.prev !== (await genesisHead(doc.receipt.digestAlg, party.signingKey.jkt))) return { ok: false, error: "seq 1 prev is not h(0) for this key" };
    }
    if (seq !== null && ext.seq !== seq + 1) return { ok: false, error: `seq ${ext.seq} does not follow ${seq}` };
    if (seq !== null && ext.prev !== head) return { ok: false, error: `receipt seq ${ext.seq}: prev does not equal the head after seq ${seq}` };
    seq = ext.seq;
    head = await nextHead(ext.prev, await receiptDigest(doc.receipt));
  }
  return { ok: true, seq, head };
}

// Section 6.4: open commitments against a party's own view of the task (this is what a client checks before countersigning).
async function checkOpenings(rc, openings, view) {
  const alg = rc.digestAlg;
  const errors = [];
  const sent = new Map(view.clientMessages.map((m) => [m.messageId, m]));
  if (rc.request.messages.length !== sent.size) errors.push("request message count differs");
  for (const { messageId, digest } of rc.request.messages) {
    const m = sent.get(messageId);
    if (!m) { errors.push(`request message ${messageId} was not sent by this client`); continue; }
    if ((await commit(alg, openings.request[messageId], await messageProjection(m, alg))) !== digest) errors.push(`request message ${messageId} commitment mismatch`);
  }
  if (rc.outcome.state !== view.task.status.state) errors.push("final state differs");
  const sm = view.task.status.message;
  if (!!sm !== !!rc.outcome.statusMessage) errors.push("status message presence differs");
  else if (sm && (await commit(alg, openings.outcome.statusMessage, await messageProjection(sm, alg))) !== rc.outcome.statusMessage.digest) errors.push("status message commitment mismatch");
  const got = new Map(view.task.artifacts.filter((a) => !isReceiptArtifact(a)).map((a) => [a.artifactId, a]));
  if (rc.outcome.artifacts.length !== got.size) errors.push("artifact count differs");
  for (const { artifactId, digest } of rc.outcome.artifacts) {
    const a = got.get(artifactId);
    if (!a) { errors.push(`artifact ${artifactId} was not received`); continue; }
    if ((await commit(alg, openings.outcome.artifacts[artifactId], await artifactProjection(a, alg))) !== digest) errors.push(`artifact ${artifactId} commitment mismatch`);
  }
  return errors;
}

// ---------------------------------------------------------------------------------------------
// Section 9: RFC 9162 Merkle tree (section 2.1), inclusion and consistency proofs, signed tree head

const hLeaf = (d) => H("sha-256", concat(Uint8Array.of(0), d));
const hNode = (l, r) => H("sha-256", concat(Uint8Array.of(1), l, r));
const split = (n) => { let k = 1; while (k * 2 < n) k *= 2; return k; }; // largest power of two smaller than n
async function mth(D) {
  if (D.length === 0) return H("sha-256", new Uint8Array(0));
  if (D.length === 1) return hLeaf(D[0]);
  const k = split(D.length);
  return hNode(await mth(D.slice(0, k)), await mth(D.slice(k)));
}
async function mthStack(D) { // RFC 9162 section 2.1.2, used only to cross-check mth()
  const st = [];
  for (let i = 0; i < D.length; i++) {
    st.push(await hLeaf(D[i]));
    let merges = 0;
    while ((i >> merges) & 1) merges++;
    for (let j = 0; j < merges; j++) { const r = st.pop(); const l = st.pop(); st.push(await hNode(l, r)); }
  }
  while (st.length > 1) { const r = st.pop(); const l = st.pop(); st.push(await hNode(l, r)); }
  return st[0];
}
async function inclusionPath(m, D) {
  if (D.length <= 1) return [];
  const k = split(D.length);
  return m < k ? [...(await inclusionPath(m, D.slice(0, k))), await mth(D.slice(k))] : [...(await inclusionPath(m - k, D.slice(k))), await mth(D.slice(0, k))];
}
async function verifyInclusion(leafHash, index, size, path, root) { // RFC 9162 section 2.1.3.2
  if (index >= size) return false;
  let fn = index;
  let sn = size - 1;
  let r = leafHash;
  for (const p of path) {
    if (sn === 0) return false;
    if (fn & 1 || fn === sn) {
      r = await hNode(p, r);
      if (!(fn & 1)) while (!(fn & 1) && fn !== 0) { fn >>= 1; sn >>= 1; }
    } else r = await hNode(r, p);
    fn >>= 1;
    sn >>= 1;
  }
  return sn === 0 && eq(r, root);
}
async function subproof(m, D, b) {
  if (m === D.length) return b ? [] : [await mth(D)];
  const k = split(D.length);
  return m <= k ? [...(await subproof(m, D.slice(0, k), b)), await mth(D.slice(k))] : [...(await subproof(m - k, D.slice(k), false)), await mth(D.slice(0, k))];
}
async function verifyConsistency(first, second, firstHash, secondHash, proofIn) { // RFC 9162 section 2.1.4.2
  if (proofIn.length === 0) return false;
  const proof = (first & (first - 1)) === 0 ? [firstHash, ...proofIn] : [...proofIn];
  let fn = first - 1;
  let sn = second - 1;
  while (fn & 1) { fn >>= 1; sn >>= 1; }
  let fr = proof[0];
  let sr = proof[0];
  for (const c of proof.slice(1)) {
    if (sn === 0) return false;
    if (fn & 1 || fn === sn) {
      fr = await hNode(c, fr);
      sr = await hNode(c, sr);
      if (!(fn & 1)) while (!(fn & 1) && fn !== 0) { fn >>= 1; sn >>= 1; }
    } else sr = await hNode(sr, c);
    fn >>= 1;
    sn >>= 1;
  }
  return eq(fr, firstHash) && eq(sr, secondHash) && sn === 0;
}
const leafData = (digestNi) => jcs({ digest: digestNi, type: "emissar-receipt" });

async function verifyAnchor(anchor, digestNi, logKeys) {
  const jwk = logKeys[anchor.log];
  if (!jwk || !(await verifyDetached(anchor.treeHead, anchor.treeHeadSignature, jwk, "emissar-tree-head+json"))) return { ok: false, error: "tree head signature" };
  const path = anchor.inclusionPath.map(b64urlToBytes);
  const ok = await verifyInclusion(await hLeaf(leafData(digestNi)), anchor.leafIndex, anchor.treeHead.treeSize, path, b64urlToBytes(anchor.treeHead.rootHash));
  return ok ? { ok: true } : { ok: false, error: "inclusion proof does not reach the signed root" };
}

// ---------------------------------------------------------------------------------------------
// The illustrative exchange: a buyer's procurement agent (client) and a supplier's freight agent (server)

const SERVER_JWK = { kty: "EC", crv: "P-256", x: "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", y: "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", d: "jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI" }; // RFC 7515 A.3
const CLIENT_JWK = { kty: "OKP", crv: "Ed25519", x: "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", d: "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A" }; // RFC 8037 A.1
const SERVER_CARD = "https://freight.example.net/.well-known/agent-card.json";
const ENDPOINT = "https://freight.example.net/a2a/v1";
const salt = async (label) => bytesToB64url((await H("sha-256", enc(`TEST-ONLY salt: ${label}`))).slice(0, 16));

const cardExtension = {
  uri: EXT,
  description: "Issues a signed Emissar Receipt as an artifact when a task reaches a terminal state.",
  required: false,
  params: {
    receiptApi: "https://freight.example.net/receipts/v0",
    jku: "https://freight.example.net/.well-known/receipt-keys.json",
    algs: ["ES256", "Ed25519"],
    digestAlgs: ["sha-256"],
    countersignWindowSeconds: 86400,
    logs: ["https://log.example.org/receipts/v1"],
  },
};

async function main() {
  const server = await loadSigner("ES256", "freight-receipts-2026-09", SERVER_JWK);
  const client = await loadSigner("Ed25519", "buyer-agent-2026-09", CLIENT_JWK);
  TRUST.keys[server.kid] = server.publicJwk;
  TRUST.keys[client.kid] = client.publicJwk;

  out("Emissar Receipt v0.1 demo (illustrative parties; RFC test keys)\n");
  out("0. Self-tests");
  const rfc8785 = JSON.parse('{"numbers":[333333333.33333329,1E30,4.50,2e-3,0.000000000000000000000000001],"string":"\\u20ac$\\u000F\\u000aA\'\\u0042\\u0022\\u005c\\\\\\"\\/","literals":[null,true,false]}');
  expect("RFC 8785 section 3.2.2 example canonicalizes to the published bytes", canonicalize(rfc8785) === '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\\u000f\\nA\'B\\"\\\\\\\\\\"/"}');
  expect("RFC 8037 A.3 JWK thumbprint of the Ed25519 test key", (await thumbprint(CLIENT_JWK)) === "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k");
  expect("RFC 6920 section 8.1 ni name for 'Hello World!'", toNi("sha-256", await H("sha-256", enc("Hello World!"))) === "ni:///sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk");
  let merkleOk = true;
  for (let n = 1; n <= 9; n++) {
    const D = Array.from({ length: n }, (_, i) => enc(`leaf ${i}`));
    const root = await mth(D);
    if (!eq(root, await mthStack(D))) merkleOk = false;
    for (let m = 0; m < n; m++) if (!(await verifyInclusion(await hLeaf(D[m]), m, n, await inclusionPath(m, D), root))) merkleOk = false;
    for (let m = 1; m < n; m++) if (!(await verifyConsistency(m, n, await mth(D.slice(0, m)), root, await subproof(m, D, true)))) merkleOk = false;
  }
  expect("RFC 9162: recursive MTH = stack algorithm; every inclusion and consistency proof verifies (n = 1..9)", merkleOk);

  // ---- Task 1: freight quote ----------------------------------------------------------------
  const requestMeta = {
    signingKey: { kid: client.kid, jkt: client.jkt, jku: "https://buyer.example.com/.well-known/receipt-keys.json" },
    agentCard: "https://buyer.example.com/.well-known/agent-card.json",
    principal: { type: "organization", id: "buyer.example.com" },
    countersign: true,
  };
  const msg1 = {
    messageId: "3b8f0c2e-5d1a-4f6b-9e7c-2a4d6f8b0c1e",
    role: "ROLE_USER",
    parts: [
      { text: "Quote freight for 12 pallets, Toronto ON to Chicago IL, pickup 2026-10-02." },
      { data: { pallets: 12, origin: "CA-ON Toronto", destination: "US-IL Chicago", pickup: "2026-10-02" }, mediaType: "application/json" },
    ],
    extensions: [EXT],
    metadata: { [EXT]: requestMeta },
  };
  const task1 = {
    id: "5f1c2d9e-8b7a-4e3c-9d21-6a0b4c7e2f13",
    contextId: "c0a1e2d3-4b5c-4d6e-8f70-81a2b3c4d5e6",
    status: {
      state: "TASK_STATE_COMPLETED",
      timestamp: "2026-09-26T14:03:12.004Z",
      message: { messageId: "9d0e1f2a-3b4c-4d5e-8f6a-7b8c9d0e1f2a", role: "ROLE_AGENT", parts: [{ text: "Quote Q-5521 is valid for 72 hours." }] },
    },
    artifacts: [{ artifactId: "quote-Q-5521", name: "Freight quote", parts: [{ data: { quoteId: "Q-5521", total: { value: "1840.00", currency: "CAD" }, validUntil: "2026-09-29T14:03:12.004Z" }, mediaType: "application/json" }] }],
  };
  const serverParty = {
    agentCard: { url: SERVER_CARD, digest: await digestOf("sha-256", { name: "Example Freight Quotes", note: "stands in for the card as served" }) },
    signingKey: { kid: server.kid, jkt: server.jkt },
    principal: { type: "organization", id: "freight.example.net" },
  };
  const clientParty = {
    agentCard: { url: requestMeta.agentCard },
    authentication: { scheme: "oauth2", subject: "buyer-agent-client-7" },
    signingKey: { kid: client.kid, jkt: client.jkt, jku: requestMeta.signingKey.jku },
    principal: requestMeta.principal,
  };

  out("\n1. Build and sign receipt 1 (task 1: freight quote)");
  const r1 = await buildReceipt({
    receiptId: "0199a1c2-7d4e-7b31-9a0f-3c5e2d1b4a60", endpoint: ENDPOINT, task: task1, clientMessages: [msg1],
    parties: { server: serverParty, client: clientParty }, acceptedAt: "2026-09-26T14:03:10.120Z", issuedAt: "2026-09-26T14:03:12.050Z", windowSeconds: 86400, salt,
  });
  const doc1 = { receipt: r1.receipt, signatures: [] };
  await signAs(doc1, "server", server, "2026-09-26T14:03:12.051Z");
  const d1 = await receiptDigest(doc1.receipt);
  out(`  receipt digest   ${d1}`);
  out(`  server chain     seq ${server.chain.seq}, head ${server.chain.head}`);
  // The receipt travels to the client as an Artifact (section 10.4).
  task1.artifacts.push({
    artifactId: `emissar-receipt-${r1.receipt.receiptId}`, name: "Emissar Receipt", extensions: [EXT],
    parts: [{ data: structuredClone(doc1), mediaType: "application/emissar-receipt+json" }, { data: r1.openings, mediaType: "application/emissar-receipt-openings+json" }],
    metadata: { [EXT]: { receiptId: r1.receipt.receiptId, receiptDigest: d1 } },
  });

  out("\n2. Client checks before countersigning (section 7.5)");
  const pre1 = await verifyReceipt(doc1, TRUST);
  expect("issuer signature valid, not yet countersigned", pre1.valid && !pre1.countersigned);
  const open1 = await checkOpenings(doc1.receipt, r1.openings, { clientMessages: [msg1], task: task1 });
  expect("request, status message and artifact commitments open against the client's own copies", open1.length === 0, open1.join("; "));
  expect("parties.client.signingKey is the client's own key", doc1.receipt.parties.client.signingKey.jkt === client.jkt);
  await signAs(doc1, "client", client, "2026-09-26T14:03:12.380Z");
  const v1 = await verifyReceipt(doc1, TRUST, { requireCountersigned: true });
  expect("receipt 1 verifies with both signatures (section 12)", v1.valid && v1.countersigned, v1.errors.join("; "));
  out(`  client chain     seq ${client.chain.seq}, head ${client.chain.head}`);

  // ---- Task 2: booking, same context, with a mandate and a payment reference ----------------------
  out("\n3. Build, sign and countersign receipt 2 (task 2: booking under a mandate, chained)");
  const mandateToken = "eyJhbGciOiJFUzI1NiJ9.ILLUSTRATIVE-MANDATE-PLACEHOLDER.c2ln"; // stands in for a presented Mandate credential
  const ap2PaymentReceipt = "eyJhbGciOiJFUzI1NiJ9.ILLUSTRATIVE-AP2-PAYMENT-RECEIPT.c2ln"; // stands in for an AP2 v0.2 Payment Receipt JWT
  const msg2 = {
    messageId: "6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9d", role: "ROLE_USER", referenceTaskIds: [task1.id],
    parts: [{ text: "Book quote Q-5521." }], extensions: [EXT], metadata: { [EXT]: requestMeta },
  };
  const task2 = {
    id: "8e2d4c6a-1b3f-4d5e-9a7c-0b2d4f6a8c1e", contextId: task1.contextId,
    status: { state: "TASK_STATE_COMPLETED", timestamp: "2026-09-26T14:05:43.918Z" },
    artifacts: [{ artifactId: "booking-B-20931", name: "Booking confirmation", parts: [{ data: { bookingId: "B-20931", quoteId: "Q-5521", pickup: "2026-10-02" }, mediaType: "application/json" }] }],
  };
  const r2 = await buildReceipt({
    receiptId: "0199a1c4-d215-7c02-8e41-5a6b7c8d9e0f", endpoint: ENDPOINT, task: task2, clientMessages: [msg2],
    parties: { server: serverParty, client: clientParty },
    mandates: [{ type: "emissar-mandate", digest: toNi("sha-256", await H("sha-256", enc(mandateToken))) }],
    payments: [{ protocol: "ap2", reference: "pay_7Qx2", receiptDigest: toNi("sha-256", await H("sha-256", enc(ap2PaymentReceipt))), amount: { value: "1840.00", currency: "CAD" } }],
    acceptedAt: "2026-09-26T14:05:41.200Z", issuedAt: "2026-09-26T14:05:43.960Z", windowSeconds: 86400, salt,
  });
  const doc2 = { receipt: r2.receipt, signatures: [] };
  await signAs(doc2, "server", server, "2026-09-26T14:05:43.961Z");
  expect("client openings check", (await checkOpenings(doc2.receipt, r2.openings, { clientMessages: [msg2], task: task2 })).length === 0);
  await signAs(doc2, "client", client, "2026-09-26T14:05:44.302Z");
  const v2 = await verifyReceipt(doc2, TRUST, { requireCountersigned: true });
  expect("receipt 2 verifies with both signatures", v2.valid && v2.countersigned, v2.errors.join("; "));
  const d2 = await receiptDigest(doc2.receipt);
  out(`  receipt digest   ${d2}`);
  const sc = await verifyChain([doc1, doc2], server.kid);
  const cc = await verifyChain([doc1, doc2], client.kid);
  expect("server chain: receipt 2 prev = head after receipt 1", sc.ok && sc.head === server.chain.head, sc.error);
  expect("client chain: receipt 2 prev = head after receipt 1", cc.ok && cc.head === client.chain.head, cc.error);
  out(`  server head      seq ${sc.seq}, ${sc.head}`);
  out(`  client head      seq ${cc.seq}, ${cc.head}`);

  // ---- Refusal ----------------------------------------------------------------------------------
  out("\n4. A receipt the client refuses (section 7.6)");
  const task3 = {
    id: "2c4e6a8b-0d1f-4a3c-9e5b-7d9f1b3d5f7a", contextId: task1.contextId,
    status: { state: "TASK_STATE_COMPLETED", timestamp: "2026-09-26T14:07:02.500Z" },
    artifacts: [{ artifactId: "status-B-20931", name: "Shipment status", parts: [{ data: { bookingId: "B-20931", status: "scheduled" }, mediaType: "application/json" }] }],
  };
  const msg3 = { messageId: "1f2e3d4c-5b6a-4978-8a6b-5c4d3e2f1a0b", role: "ROLE_USER", parts: [{ text: "Status of booking B-20931?" }], extensions: [EXT], metadata: { [EXT]: requestMeta } };
  const recorded = structuredClone(task3); // the server records a different outcome than it sent
  recorded.artifacts[0].parts[0].data.status = "delivered";
  const r3 = await buildReceipt({
    receiptId: "0199a1c6-0a3b-7e44-b2c5-6d7e8f9a0b1c", endpoint: ENDPOINT, task: recorded, clientMessages: [msg3],
    parties: { server: serverParty, client: clientParty }, acceptedAt: "2026-09-26T14:07:01.900Z", issuedAt: "2026-09-26T14:07:02.540Z", windowSeconds: 86400, salt,
  });
  const doc3 = { receipt: r3.receipt, signatures: [] };
  await signAs(doc3, "server", server, "2026-09-26T14:07:02.541Z");
  const open3 = await checkOpenings(doc3.receipt, r3.openings, { clientMessages: [msg3], task: task3 });
  expect("client detects the mismatch and does not countersign", open3.length > 0, open3.join("; "));
  const refusal = { refusal: { receiptId: r3.receipt.receiptId, receiptDigest: await receiptDigest(r3.receipt), reason: "outcome_mismatch", refusedAt: "2026-09-26T14:07:02.900Z" }, signatures: [] };
  refusal.signatures.push(await signDetached(refusal.refusal, client, "emissar-receipt-refusal+json"));
  expect("signed refusal verifies with the client key", await verifyDetached(refusal.refusal, refusal.signatures[0], client.publicJwk, "emissar-receipt-refusal+json"));
  const v3 = await verifyReceipt(doc3, TRUST);
  expect("receipt 3 stays valid as issuer-signed only (countersigned: false)", v3.valid && !v3.countersigned);

  // ---- Anchoring ----------------------------------------------------------------------------------
  out("\n5. Anchor receipts in an RFC 9162 Merkle log (section 9)");
  const others = await Promise.all([1, 2, 3].map(async (i) => toNi("sha-256", await H("sha-256", enc(`another party's receipt ${i}`)))));
  const entries = [others[0], d1, others[1], d2, others[2]];
  const D = entries.map(leafData);
  const root = await mth(D);
  const logKey = await (async () => {
    const kp = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
    return { alg: "ES256", kid: "log-demo-key", privateKey: kp.privateKey, publicJwk: { ...(await subtle.exportKey("jwk", kp.publicKey)), kid: "log-demo-key" } };
  })();
  const treeHead = { log: cardExtension.params.logs[0], treeSize: D.length, rootHash: bytesToB64url(root), timestamp: "2026-09-26T14:10:00.000Z" };
  const treeHeadSignature = await signDetached(treeHead, logKey, "emissar-tree-head+json");
  const anchorFor = async (i) => ({ type: "rfc9162-sha256", log: treeHead.log, leafIndex: i, inclusionPath: (await inclusionPath(i, D)).map(bytesToB64url), treeHead, treeHeadSignature });
  const logKeys = { [treeHead.log]: logKey.publicJwk };
  const a1 = await anchorFor(1);
  const a2 = await anchorFor(3);
  out(`  tree size ${D.length}, root ${bytesToB64url(root)}`);
  out(`  receipt 1 at leaf 1, path length ${a1.inclusionPath.length}; receipt 2 at leaf 3, path length ${a2.inclusionPath.length}`);
  expect("receipt 1 inclusion proof verifies against the signed tree head", (await verifyAnchor(a1, d1, logKeys)).ok);
  expect("receipt 2 inclusion proof verifies against the signed tree head", (await verifyAnchor(a2, d2, logKeys)).ok);
  const earlier = await mth(D.slice(0, 2));
  expect("consistency proof: the 2-entry tree is a prefix of the 5-entry tree", await verifyConsistency(2, 5, earlier, root, await subproof(2, D, true)));
  doc1.anchors = [a1];
  doc2.anchors = [a2];

  // ---- Failure cases ------------------------------------------------------------------------------
  out("\n6. Failure cases (each MUST be rejected)");
  const tampered = structuredClone(doc2);
  tampered.receipt.payments[0].amount.value = "18400.00";
  const vt = await verifyReceipt(tampered, TRUST);
  expect("tampered field (payment amount): rejected", !vt.valid, vt.errors.join("; "));

  const oneSig = structuredClone(doc1);
  oneSig.signatures = oneSig.signatures.filter((s) => decodeHeader(s.protected)[EXT].role !== "client");
  const vo = await verifyReceipt(oneSig, TRUST, { requireCountersigned: true });
  expect("missing second signature under a countersign-required policy: rejected", !vo.valid, vo.errors.join("; "));

  // The issuer rewrites receipt 1 after the fact and re-signs it with its own key. Every signature on the
  // rewritten receipt is valid, but receipt 2 still commits to the original chain.
  const forger = await loadSigner("ES256", server.kid, SERVER_JWK);
  const rewritten = { receipt: structuredClone(doc1.receipt), signatures: [] };
  rewritten.receipt.outcome.state = "TASK_STATE_REJECTED";
  await signAs(rewritten, "server", forger, "2026-09-26T14:03:12.051Z");
  const vr = await verifyReceipt(rewritten, TRUST);
  const br = await verifyChain([rewritten, doc2], server.kid);
  expect("rewritten receipt 1 has a valid issuer signature on its own", vr.valid);
  expect("broken chain: receipt 2 prev no longer matches: rejected", !br.ok, br.error);

  const wrongPath = structuredClone(a1);
  wrongPath.inclusionPath[0] = a2.inclusionPath[0];
  const wp = await verifyAnchor(wrongPath, d1, logKeys);
  expect("wrong inclusion proof (swapped sibling hash): rejected", !wp.ok, wp.error);
  const wrongLeaf = await verifyAnchor(a1, d2, logKeys);
  expect("inclusion proof presented for a different receipt: rejected", !wrongLeaf.ok, wrongLeaf.error);

  const badSalt = structuredClone(r1.openings);
  badSalt.request[msg1.messageId] = await salt("guess");
  const bs = await checkOpenings(doc1.receipt, badSalt, { clientMessages: [msg1], task: task1 });
  expect("opening with a wrong salt: commitment does not open", bs.length > 0, bs[0]);

  out(`\n${failures === 0 ? "ALL CHECKS PASSED" : `${failures} CHECK(S) FAILED`}`);
  if (JSON_MODE) {
    const headers = [doc1, doc2, doc3].flatMap((d) => d.signatures.map((s) => decodeHeader(s.protected)));
    console.log(JSON.stringify({
      receipts: [doc1, doc2, doc3],
      openings: [r1.openings, r2.openings, r3.openings],
      protectedHeaders: headers,
      refusal,
      anchors: [a1, a2],
      cardExtension,
      requestMetadata: requestMeta,
      requestMessage: msg1,
      finalTask: task1,
      invalid: { tampered, rewritten },
    }, null, 2));
  }
  process.exitCode = failures === 0 ? 0 : 1;
}

await main();
