// Public protocol only. Run in a browser module or Node >= 20. No private endpoint or secret.
export function canonical(value) {
  if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
  if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
  if (value && typeof value === 'object') return `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
  throw new Error('Unsupported canonical value');
}
const encode = bytes => btoa(String.fromCharCode(...new Uint8Array(bytes))).replaceAll('+','-').replaceAll('/','_').replace(/=+$/u,'');
const decode = str => Uint8Array.from(atob(str.replaceAll('-','+').replaceAll('_','/')), c => c.charCodeAt(0));
export async function hash(value) { return encode(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(canonical(value)))); }
export async function verifySignature(payload, signature, trustedJwk) {
  if (signature?.algorithm !== 'ES256' || !trustedJwk || trustedJwk.d || trustedJwk.kty !== 'EC' || trustedJwk.crv !== 'P-256') return false;
  const pub = {kty:'EC',crv:'P-256',x:trustedJwk.x,y:trustedJwk.y};
  if (signature.key_id !== await hash(pub)) return false;
  try {
    const key = await crypto.subtle.importKey('jwk', pub, {name:'ECDSA',namedCurve:'P-256'}, false, ['verify']);
    return await crypto.subtle.verify({name:'ECDSA',hash:'SHA-256'},key,decode(signature.value),new TextEncoder().encode(canonical(payload)));
  } catch { return false; }
}
export async function merkleRoot(records) {
  let layer = await Promise.all(records.map(r => hash({domain:'cassie-proof-leaf-v1',event_id:r.envelope.event_id,event_hash:r.event_hash})));
  if (!layer.length) return hash({domain:'cassie-proof-empty-v1'});
  while (layer.length > 1) {
    const next = [];
    for (let i=0;i<layer.length;i+=2) next.push(await hash({domain:'cassie-proof-node-v1',left:layer[i],right:layer[i+1]||layer[i]}));
    layer = next;
  }
  return layer[0];
}
export async function verifyBundle(bundle, trustedJwk, previousBundle = null) {
  const fail = reason => ({valid:false,reason});
  if (!bundle?.payload || !Array.isArray(bundle.payload.events)) return fail('INVALID_BUNDLE');
  const p=bundle.payload;
  if (await hash(p) !== bundle.checkpoint_id) return fail('CHECKPOINT_HASH');
  if (!await verifySignature(p,bundle.signature,trustedJwk)) return fail('CHECKPOINT_SIGNATURE');
  if (p.previous_checkpoint_id && (!previousBundle || previousBundle.checkpoint_id !== p.previous_checkpoint_id || await hash(previousBundle.payload) !== previousBundle.checkpoint_id || !await verifySignature(previousBundle.payload,previousBundle.signature,trustedJwk))) return fail('PREVIOUS_CHECKPOINT_REQUIRED');
  if (p.event_count !== p.events.length) return fail('MISSING_EVENT');
  const seen=new Map();let sequence=-1;
  const levels=new Set(['unknown','undisclosed','self_declared','operator_declared','gateway_observed','provider_attested']);
  for (const record of p.events) {
    const e=record.envelope;
    if (!e || seen.has(e.event_id) || e.source_ledger_sequence <= sequence) return fail('EVENT_ORDER_OR_DUPLICATE');
    if (!levels.has(e.model_provenance_level)) return fail('INVALID_PROVENANCE');
    if (await hash(e) !== record.event_hash || !await verifySignature(e,record.signature,trustedJwk)) return fail('EVENT_HASH_OR_SIGNATURE');
    if (e.parent_artifact_ids.length !== e.parent_commitments.length) return fail('PARENT_MEMBERSHIP');
    for (const parent of e.parent_commitments) if (!e.parent_artifact_ids.includes(parent.event_id) || seen.get(parent.event_id) !== parent.event_hash) return fail('PARENT_HASH_OR_MISSING_EVENT');
    if (await hash(e.parent_commitments.map(x=>x.event_hash)) !== e.input_commitment_hash) return fail('INPUT_COMMITMENT');
    seen.set(e.event_id,record.event_hash);sequence=e.source_ledger_sequence;
  }
  if (await merkleRoot(p.events) !== p.merkle_root) return fail('MERKLE_ROOT');
  if (await hash({records:p.events.map(r=>r.event_hash),runs:p.runs,metrics:p.summary}) !== p.content_hash) return fail('BUNDLE_CONTENT_HASH');
  return {valid:true,events:p.events.length,checkpoint_id:bundle.checkpoint_id,scope:'Publisher signatures and published membership verified; semantic truth, origin labels and operator independence require external corroboration.'};
}
