import { createHash, createPublicKey, verify as verifySignature } from 'node:crypto'

export class AssuranceExclusivityError extends Error {}

const PROFILE = 'glyph.assurance-exclusivity/0.1-experimental'
const CONSTITUTION = 'glyph.witness-assurance-constitution/0.2-model-only'
const BINDING_PROFILE = 'glyph.assurance-binding-statement/1'
const WITNESS_PROFILE = 'glyph.assurance-portfolio-witness/1'
const MECHANISMS = ['BANK_ESCROW', 'CUSTODIAN_LOCK', 'ONCHAIN_LOCK', 'SURETY_GUARANTEE']

function ordinal(a, b) {
  return a < b ? -1 : a > b ? 1 : 0
}

function plain(value) {
  return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype
}

function exact(value, fields, label) {
  if (!plain(value)) throw new AssuranceExclusivityError(`${label} must be an object`)
  const actual = Object.keys(value).sort(ordinal)
  const expected = [...fields].sort(ordinal)
  if (actual.length !== expected.length || actual.some((field, index) => field !== expected[index])) {
    throw new AssuranceExclusivityError(`${label} fields changed`)
  }
  return value
}

function text(value, label) {
  if (typeof value !== 'string' || !/^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/.test(value)) throw new AssuranceExclusivityError(`${label} must be a non-empty printable ASCII string without edge whitespace`)
  return value
}

function safeInteger(value, label) {
  if (!Number.isSafeInteger(value) || value < 0) throw new AssuranceExclusivityError(`${label} must be a non-negative safe integer`)
  return value
}

function digestValue(value, label) {
  if (typeof value !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(value)) throw new AssuranceExclusivityError(`${label} must be a lowercase sha256 digest`)
  return value
}

function canonicalValue(value) {
  if (value === null || typeof value === 'boolean' || typeof value === 'string') return value
  if (typeof value === 'number') {
    if (!Number.isSafeInteger(value)) throw new AssuranceExclusivityError('canonical numbers must be safe integers')
    return value
  }
  if (Array.isArray(value)) return value.map(canonicalValue)
  if (!plain(value)) throw new AssuranceExclusivityError('canonical values must be JSON values')
  const result = Object.create(null)
  for (const key of Object.keys(value).sort(ordinal)) result[key] = canonicalValue(value[key])
  return result
}

export function canonical(value) {
  return JSON.stringify(canonicalValue(value))
}

export function sha256(value) {
  return `sha256:${createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : canonical(value)).digest('hex')}`
}

function strictBase64(value, label) {
  text(value, label)
  const decoded = Buffer.from(value, 'base64')
  if (decoded.length === 0 || decoded.toString('base64') !== value) throw new AssuranceExclusivityError(`${label} must be canonical base64`)
  return decoded
}

function portfolioPayload(snapshot) {
  return {
    allocations: snapshot.allocations,
    capacity_id: snapshot.capacity_id,
    challenge_horizon: snapshot.challenge_horizon,
    complete: snapshot.complete,
    declared_allocation_count: snapshot.declared_allocation_count,
    portfolio_id: snapshot.portfolio_id,
    profile: snapshot.profile,
    total_capacity: snapshot.total_capacity,
    unit: snapshot.unit,
  }
}

export function portfolioRoot(snapshot) {
  return sha256(portfolioPayload(snapshot))
}

function validateAllocation(allocation, index) {
  exact(allocation, ['allocation_id', 'amount', 'beneficiary', 'binding_id', 'covenant_id', 'encumbered_through'], `allocation[${index}]`)
  for (const field of ['allocation_id', 'beneficiary', 'binding_id', 'covenant_id']) text(allocation[field], `allocation[${index}].${field}`)
  safeInteger(allocation.amount, `allocation[${index}].amount`)
  safeInteger(allocation.encumbered_through, `allocation[${index}].encumbered_through`)
}

export function auditPortfolio(snapshot, acceptedRoot) {
  exact(snapshot, ['allocations', 'capacity_id', 'challenge_horizon', 'complete', 'declared_allocation_count', 'portfolio_id', 'portfolio_root', 'profile', 'total_capacity', 'unit'], 'portfolio snapshot')
  if (snapshot.profile !== 'glyph.assurance-capacity-portfolio/1') throw new AssuranceExclusivityError('portfolio profile is not accepted')
  text(snapshot.portfolio_id, 'portfolio_id')
  text(snapshot.capacity_id, 'capacity_id')
  text(snapshot.unit, 'unit')
  safeInteger(snapshot.total_capacity, 'total_capacity')
  safeInteger(snapshot.challenge_horizon, 'challenge_horizon')
  if (snapshot.complete !== true) throw new AssuranceExclusivityError('portfolio snapshot is not complete')
  if (!Array.isArray(snapshot.allocations) || snapshot.allocations.length > 64) throw new AssuranceExclusivityError('allocations must be an array of at most 64 members')
  safeInteger(snapshot.declared_allocation_count, 'declared_allocation_count')
  if (snapshot.declared_allocation_count !== snapshot.allocations.length) throw new AssuranceExclusivityError('portfolio allocation count is incomplete')
  digestValue(snapshot.portfolio_root, 'portfolio_root')
  const computedRoot = portfolioRoot(snapshot)
  if (snapshot.portfolio_root !== computedRoot) throw new AssuranceExclusivityError('portfolio root does not match the complete snapshot')
  if (acceptedRoot !== undefined && acceptedRoot !== computedRoot) throw new AssuranceExclusivityError('portfolio root is not receiver-pinned')

  const allocationIds = new Set()
  const bindingIds = new Set()
  let allocated = 0
  for (const [index, allocation] of snapshot.allocations.entries()) {
    validateAllocation(allocation, index)
    if (allocationIds.has(allocation.allocation_id)) throw new AssuranceExclusivityError('allocation identifier is reused in the complete portfolio')
    if (bindingIds.has(allocation.binding_id)) throw new AssuranceExclusivityError('binding identifier is reused in the complete portfolio')
    allocationIds.add(allocation.allocation_id)
    bindingIds.add(allocation.binding_id)
    if (allocation.encumbered_through < snapshot.challenge_horizon) throw new AssuranceExclusivityError('allocation releases before the challenge horizon')
    allocated += allocation.amount
    if (!Number.isSafeInteger(allocated)) throw new AssuranceExclusivityError('allocated amount exceeds safe-integer range')
  }

  return {
    allocated,
    available_inside_snapshot: allocated <= snapshot.total_capacity ? snapshot.total_capacity - allocated : 0,
    capacity_id: snapshot.capacity_id,
    external_encumbrance: 'NOT_COMPUTED',
    portfolio_root: computedRoot,
    status: allocated <= snapshot.total_capacity ? 'DECLARED' : 'CAPACITY_EXCEEDED',
    total_capacity: snapshot.total_capacity,
    unit: snapshot.unit,
  }
}

function authority(policy, mechanism) {
  exact(policy.binding_authorities, MECHANISMS, 'binding authorities')
  const accepted = policy.binding_authorities[mechanism]
  exact(accepted, ['authority_id', 'public_key_spki_b64'], `${mechanism} authority`)
  text(accepted.authority_id, `${mechanism} authority_id`)
  strictBase64(accepted.public_key_spki_b64, `${mechanism} public key`)
  return accepted
}

function mechanismPolicy(policy, mechanism) {
  exact(policy.mechanism_policies, MECHANISMS, 'mechanism policies')
  const accepted = policy.mechanism_policies[mechanism]
  if (mechanism === 'ONCHAIN_LOCK') {
    exact(accepted, ['chain_id', 'contract_id', 'genesis_hash', 'minimum_finality_depth', 'statement_profile'], 'on-chain receiver policy')
    text(accepted.chain_id, 'accepted on-chain chain_id')
    text(accepted.contract_id, 'accepted on-chain contract_id')
    digestValue(accepted.genesis_hash, 'accepted on-chain genesis_hash')
    safeInteger(accepted.minimum_finality_depth, 'accepted on-chain minimum_finality_depth')
  } else {
    exact(accepted, ['statement_profile'], `${mechanism} receiver policy`)
  }
  if (accepted.statement_profile !== BINDING_PROFILE) throw new AssuranceExclusivityError(`${mechanism} statement profile is not receiver-pinned`)
  return accepted
}

function validatePortfolioContract(contract, snapshot) {
  exact(contract, ['allocation_ids', 'binding_ids', 'capacity_id', 'portfolio_id', 'total_capacity', 'unit'], 'receiver portfolio contract')
  text(contract.capacity_id, 'portfolio capacity_id')
  text(contract.portfolio_id, 'portfolio contract portfolio_id')
  text(contract.unit, 'portfolio contract unit')
  safeInteger(contract.total_capacity, 'portfolio contract total_capacity')
  if (!Array.isArray(contract.allocation_ids) || !Array.isArray(contract.binding_ids)) throw new AssuranceExclusivityError('portfolio contract identifiers must be arrays')
  for (const [index, value] of contract.allocation_ids.entries()) text(value, `portfolio contract allocation_ids[${index}]`)
  for (const [index, value] of contract.binding_ids.entries()) text(value, `portfolio contract binding_ids[${index}]`)
  const allocationIds = snapshot.allocations.map((item) => item.allocation_id).sort(ordinal)
  const bindingIds = snapshot.allocations.map((item) => item.binding_id).sort(ordinal)
  if (canonical(contract.allocation_ids) !== canonical([...contract.allocation_ids].sort(ordinal)) || canonical(contract.binding_ids) !== canonical([...contract.binding_ids].sort(ordinal))) {
    throw new AssuranceExclusivityError('portfolio contract identifiers are not ASCII ordered')
  }
  if (canonical(contract.allocation_ids) !== canonical(allocationIds) || canonical(contract.binding_ids) !== canonical(bindingIds)) throw new AssuranceExclusivityError('portfolio does not contain the receiver-pinned allocation registry')
  if (contract.capacity_id !== snapshot.capacity_id || contract.portfolio_id !== snapshot.portfolio_id || contract.total_capacity !== snapshot.total_capacity || contract.unit !== snapshot.unit) throw new AssuranceExclusivityError('portfolio does not match the receiver-pinned capacity identity')
}

function mechanismDetails(mechanism, details, statement) {
  if (mechanism === 'BANK_ESCROW') {
    exact(details, ['account_ref', 'escrow_ref', 'release_position'], 'bank escrow details')
    text(details.account_ref, 'bank account_ref')
    text(details.escrow_ref, 'bank escrow_ref')
    safeInteger(details.release_position, 'bank release_position')
  } else if (mechanism === 'CUSTODIAN_LOCK') {
    exact(details, ['custody_account', 'lock_ref', 'release_position'], 'custodian lock details')
    text(details.custody_account, 'custody_account')
    text(details.lock_ref, 'custodian lock_ref')
    safeInteger(details.release_position, 'custodian release_position')
  } else if (mechanism === 'SURETY_GUARANTEE') {
    exact(details, ['expiry_position', 'guarantee_ref', 'limit'], 'surety guarantee details')
    safeInteger(details.expiry_position, 'surety expiry_position')
    text(details.guarantee_ref, 'surety guarantee_ref')
    safeInteger(details.limit, 'surety limit')
    if (details.limit !== statement.amount) throw new AssuranceExclusivityError('surety limit does not equal the bound amount')
  } else if (mechanism === 'ONCHAIN_LOCK') {
    exact(details, ['chain_id', 'contract_id', 'finality_depth', 'genesis_hash', 'headers', 'lock_block', 'lock_tx', 'release_position'], 'on-chain lock details')
    for (const field of ['chain_id', 'contract_id']) text(details[field], `on-chain ${field}`)
    for (const field of ['genesis_hash', 'lock_tx']) digestValue(details[field], `on-chain ${field}`)
    safeInteger(details.finality_depth, 'on-chain finality_depth')
    safeInteger(details.lock_block, 'on-chain lock_block')
    safeInteger(details.release_position, 'on-chain release_position')
    if (!Array.isArray(details.headers) || details.headers.length === 0 || details.headers.length > 64) throw new AssuranceExclusivityError('on-chain headers must contain 1 to 64 members')
    let previous = details.genesis_hash
    for (const [index, header] of details.headers.entries()) {
      exact(header, ['block_hash', 'height', 'previous_hash', 'transactions_root'], `on-chain header[${index}]`)
      safeInteger(header.height, `on-chain header[${index}].height`)
      for (const field of ['block_hash', 'previous_hash', 'transactions_root']) digestValue(header[field], `on-chain header[${index}].${field}`)
      if (header.height !== details.lock_block + index) throw new AssuranceExclusivityError('on-chain block heights are not consecutive successors')
      if (header.previous_hash !== previous) throw new AssuranceExclusivityError('on-chain header continuity failed')
      const expectedHash = sha256({ height: header.height, previous_hash: header.previous_hash, transactions_root: header.transactions_root })
      if (header.block_hash !== expectedHash) throw new AssuranceExclusivityError('on-chain block hash failed')
      if (index === 0 && (header.height !== details.lock_block || header.transactions_root !== sha256({ lock_tx: details.lock_tx }))) {
        throw new AssuranceExclusivityError('on-chain lock transaction is not committed at lock_block')
      }
      previous = header.block_hash
    }
    const observedDepth = details.headers.length - 1
    if (observedDepth < details.finality_depth) throw new AssuranceExclusivityError('on-chain finality policy is not satisfied')
  } else {
    throw new AssuranceExclusivityError('binding mechanism is not supported')
  }

  const release = details.release_position ?? details.expiry_position
  if (release < statement.horizon) throw new AssuranceExclusivityError('binding releases before its challenge horizon')
  return release
}

function verifyBindingRecord(record, policy) {
  exact(record, ['signature_b64', 'statement'], 'binding record')
  const statement = exact(record.statement, ['amount', 'authority_id', 'beneficiary', 'binding_id', 'control_domain', 'covenant_id', 'evidence_time', 'horizon', 'mechanism', 'mechanism_details', 'portfolio_root', 'profile', 'status', 'unit'], 'binding statement')
  if (statement.profile !== BINDING_PROFILE) throw new AssuranceExclusivityError('binding statement profile is not accepted')
  if (!MECHANISMS.includes(statement.mechanism)) throw new AssuranceExclusivityError('binding mechanism is not accepted')
  for (const field of ['authority_id', 'beneficiary', 'binding_id', 'control_domain', 'covenant_id', 'unit']) text(statement[field], `binding ${field}`)
  safeInteger(statement.amount, 'binding amount')
  safeInteger(statement.evidence_time, 'binding evidence_time')
  safeInteger(statement.horizon, 'binding horizon')
  digestValue(statement.portfolio_root, 'binding portfolio_root')
  if (statement.status !== 'BOUND') throw new AssuranceExclusivityError('binding status is not BOUND')
  mechanismDetails(statement.mechanism, statement.mechanism_details, statement)

  const accepted = authority(policy, statement.mechanism)
  if (statement.authority_id !== accepted.authority_id) throw new AssuranceExclusivityError('binding authority is not receiver-pinned')
  const publicKey = createPublicKey({ key: strictBase64(accepted.public_key_spki_b64, 'binding public key'), format: 'der', type: 'spki' })
  if (publicKey.asymmetricKeyType !== 'ed25519') throw new AssuranceExclusivityError('binding authority key must be Ed25519')
  const signature = strictBase64(record.signature_b64, 'binding signature')
  if (!verifySignature(null, Buffer.from(canonical(statement)), publicKey, signature)) throw new AssuranceExclusivityError('binding signature is invalid')
  const acceptedMechanism = mechanismPolicy(policy, statement.mechanism)
  if (statement.mechanism === 'ONCHAIN_LOCK') {
    const details = statement.mechanism_details
    if (details.chain_id !== acceptedMechanism.chain_id || details.contract_id !== acceptedMechanism.contract_id || details.genesis_hash !== acceptedMechanism.genesis_hash) {
      throw new AssuranceExclusivityError('on-chain jurisdiction is not receiver-pinned')
    }
    if (details.finality_depth < acceptedMechanism.minimum_finality_depth) throw new AssuranceExclusivityError('on-chain finality depth is below receiver policy')
  }
  return statement
}

function onchainLockTransaction(allocation, statement) {
  return sha256({
    allocation_id: allocation.allocation_id,
    amount: statement.amount,
    beneficiary: statement.beneficiary,
    binding_id: statement.binding_id,
    covenant_id: statement.covenant_id,
    horizon: statement.horizon,
    portfolio_root: statement.portfolio_root,
    profile: 'glyph.assurance-onchain-lock-payload/1',
    unit: statement.unit,
  })
}

export function evaluateExclusiveBinding(input) {
  exact(input, ['binding', 'policy', 'snapshot'], 'exclusive binding input')
  const { binding, policy, snapshot } = input
  exact(policy, ['accepted_portfolio_root', 'binding_authorities', 'evaluation_time', 'mechanism_policies', 'portfolio_contract', 'profile'], 'receiver policy')
  if (policy.profile !== 'glyph.assurance-exclusivity-receiver-policy/1') throw new AssuranceExclusivityError('receiver policy profile is not accepted')
  safeInteger(policy.evaluation_time, 'policy evaluation_time')
  digestValue(policy.accepted_portfolio_root, 'policy accepted_portfolio_root')
  const portfolio = auditPortfolio(snapshot, policy.accepted_portfolio_root)
  validatePortfolioContract(policy.portfolio_contract, snapshot)
  if (portfolio.status !== 'DECLARED') throw new AssuranceExclusivityError('an overallocated portfolio cannot be exclusively bound')
  const statement = verifyBindingRecord(binding, policy)
  if (statement.portfolio_root !== portfolio.portfolio_root) throw new AssuranceExclusivityError('binding does not bind the complete portfolio root')
  if (statement.evidence_time > policy.evaluation_time) throw new AssuranceExclusivityError('binding evidence is from the future')
  const releasePosition = statement.mechanism_details.release_position ?? statement.mechanism_details.expiry_position
  if (releasePosition <= policy.evaluation_time) throw new AssuranceExclusivityError('binding is expired at the receiver evaluation position')
  const allocation = snapshot.allocations.find((item) => item.binding_id === statement.binding_id)
  if (!allocation) throw new AssuranceExclusivityError('binding is not allocated in the complete portfolio')
  for (const field of ['amount', 'beneficiary', 'covenant_id']) {
    if (allocation[field] !== statement[field]) throw new AssuranceExclusivityError(`binding ${field} disagrees with the allocation`)
  }
  if (allocation.encumbered_through !== statement.horizon) throw new AssuranceExclusivityError('binding horizon disagrees with the allocation')
  if (statement.unit !== portfolio.unit) throw new AssuranceExclusivityError('binding unit disagrees with the complete portfolio')
  if (statement.mechanism === 'ONCHAIN_LOCK' && statement.mechanism_details.lock_tx !== onchainLockTransaction(allocation, statement)) {
    throw new AssuranceExclusivityError('on-chain transaction does not bind the selected allocation')
  }
  return {
    accepted_mechanism: statement.mechanism,
    allocation_id: allocation.allocation_id,
    amount: statement.amount,
    beneficiary: statement.beneficiary,
    binding_id: statement.binding_id,
    control_domain: statement.control_domain,
    covenant_id: statement.covenant_id,
    evidence_time: statement.evidence_time,
    external_encumbrance: 'NOT_COMPUTED',
    horizon: statement.horizon,
    jurisdiction: 'ACCEPTED_MECHANISM_DECLARED_JURISDICTION',
    outside_accepted_portfolio: 'NOT_COMPUTED',
    portfolio_contract: sha256(policy.portfolio_contract),
    receiver_policy: sha256(policy),
    stage: 'EXCLUSIVELY_BOUND',
    unit: statement.unit,
  }
}

function verifyWitness(view, root) {
  exact(view, ['signature_b64', 'statement'], 'witness view')
  const statement = exact(view.statement, ['checkpoint_position', 'log_id', 'operator_id', 'portfolio_root', 'profile'], 'witness statement')
  if (statement.profile !== WITNESS_PROFILE) throw new AssuranceExclusivityError('witness profile is not accepted')
  for (const field of ['log_id', 'operator_id']) text(statement[field], `witness ${field}`)
  safeInteger(statement.checkpoint_position, 'witness checkpoint_position')
  digestValue(statement.portfolio_root, 'witness portfolio_root')
  exact(root, ['operator_id', 'public_key_spki_b64'], 'witness root')
  if (root.operator_id !== statement.operator_id) throw new AssuranceExclusivityError('witness operator is not receiver-pinned')
  const key = createPublicKey({ key: strictBase64(root.public_key_spki_b64, 'witness public key'), format: 'der', type: 'spki' })
  if (key.asymmetricKeyType !== 'ed25519') throw new AssuranceExclusivityError('witness root key must be Ed25519')
  if (!verifySignature(null, Buffer.from(canonical(statement)), key, strictBase64(view.signature_b64, 'witness signature'))) throw new AssuranceExclusivityError('witness signature is invalid')
  return statement
}

export function evaluateWitnessedView(input) {
  exact(input, ['snapshot', 'view', 'witnessRoot'], 'witnessed view input')
  const { snapshot, view, witnessRoot } = input
  const portfolio = auditPortfolio(snapshot, snapshot.portfolio_root)
  if (portfolio.status !== 'DECLARED') throw new AssuranceExclusivityError('witnessed view exceeds its declared capacity')
  const statement = verifyWitness(view, witnessRoot)
  if (statement.portfolio_root !== portfolio.portfolio_root) throw new AssuranceExclusivityError('witness did not commit to this portfolio root')
  return {
    allocation_count: snapshot.allocations.length,
    allocated: portfolio.allocated,
    capacity_id: portfolio.capacity_id,
    exclusivity: 'NOT_ESTABLISHED',
    external_encumbrance: 'NOT_COMPUTED',
    portfolio_root: portfolio.portfolio_root,
    stage: 'WITNESSED',
    total_capacity: portfolio.total_capacity,
    unit: portfolio.unit,
    witness_log_id: statement.log_id,
    witness_operator_id: statement.operator_id,
  }
}

export function evaluateForumCommitment(input) {
  exact(input, ['accepted_forum_authority', 'accepted_portfolio', 'commitment', 'reliance_position'], 'forum commitment input')
  const { accepted_forum_authority, accepted_portfolio, commitment, reliance_position } = input
  safeInteger(reliance_position, 'reliance_position')
  const portfolio = auditPortfolio(accepted_portfolio, accepted_portfolio.portfolio_root)
  exact(accepted_forum_authority, ['authority_id', 'public_key_spki_b64'], 'accepted forum authority')
  exact(commitment, ['signature_b64', 'statement'], 'forum commitment record')
  const statement = exact(commitment.statement, ['committed_position', 'covenant_id', 'forum_authority_id', 'forum_id', 'portfolio_root', 'profile'], 'forum commitment statement')
  if (statement.profile !== 'glyph.assurance-forum-commitment/1') throw new AssuranceExclusivityError('forum commitment profile is not accepted')
  text(statement.covenant_id, 'forum covenant_id')
  text(statement.forum_authority_id, 'forum authority')
  text(statement.forum_id, 'forum id')
  digestValue(statement.portfolio_root, 'forum portfolio_root')
  if (statement.portfolio_root !== portfolio.portfolio_root) throw new AssuranceExclusivityError('forum commitment does not bind the receiver-pinned portfolio')
  if (!accepted_portfolio.allocations.some((allocation) => allocation.covenant_id === statement.covenant_id)) throw new AssuranceExclusivityError('forum commitment covenant is not present in the receiver-pinned portfolio')
  if (statement.forum_authority_id !== accepted_forum_authority.authority_id) throw new AssuranceExclusivityError('forum authority is not receiver-pinned')
  const key = createPublicKey({ key: strictBase64(accepted_forum_authority.public_key_spki_b64, 'forum public key'), format: 'der', type: 'spki' })
  if (key.asymmetricKeyType !== 'ed25519') throw new AssuranceExclusivityError('forum authority key must be Ed25519')
  if (!verifySignature(null, Buffer.from(canonical(statement)), key, strictBase64(commitment.signature_b64, 'forum signature'))) throw new AssuranceExclusivityError('forum commitment signature is invalid')
  if (safeInteger(statement.committed_position, 'forum committed_position') >= reliance_position) throw new AssuranceExclusivityError('forum was selected at or after reliance')
  return {
    authority_id: statement.forum_authority_id,
    commitment_digest: sha256(commitment),
    committed_position: statement.committed_position,
    covenant_id: statement.covenant_id,
    forum_id: statement.forum_id,
    portfolio_root: statement.portfolio_root,
    reliance_position,
    state: 'FORUM_PRECOMMITTED',
  }
}

export function evaluateContext(context) {
  exact(context, ['binding_cases', 'constitution', 'forum_case', 'kernel', 'profile', 'qingdao'], 'assurance exclusivity context')
  if (context.profile !== PROFILE || context.constitution !== CONSTITUTION) throw new AssuranceExclusivityError('context profile is not accepted')
  exact(context.kernel, ['A', 'E', 'H', 'R', 'X', 'Φ'], 'constitutional kernel')
  const expectedKernel = {
    A: ['CORRECTION', 'EVIDENCE', 'EXECUTION', 'FORUM', 'RECOURSE'],
    E: ['RECEIVER_PINNED_SIGNATURE', 'LOCAL_CHAIN_FINALITY', 'WITNESSED_HISTORY'],
    H: ['RELIANCE_POSITION', 'CHALLENGE_HORIZON', 'EXPIRY', 'CORRECTION', 'CLOSURE', 'NOVATION'],
    R: ['WITNESS', 'BENEFICIARY', 'CAPITAL_PROVIDER', 'FORUM', 'EXECUTION_RAIL'],
    X: ['EXPOSURE', 'CAPACITY_PORTFOLIO', 'ALLOCATION', 'BENEFICIARY', 'BINDING_MECHANISM'],
    'Φ': ['OBJECTIVE', 'SERVICE_LEVEL', 'JUDGMENT_DEPENDENT'],
  }
  if (canonical(context.kernel) !== canonical(expectedKernel)) throw new AssuranceExclusivityError('constitutional kernel changed')
  if (!Array.isArray(context.binding_cases) || context.binding_cases.length !== MECHANISMS.length) throw new AssuranceExclusivityError('all four typed binding cases are required')
  const bindingCases = context.binding_cases.map((item) => {
    exact(item, ['binding', 'policy', 'snapshot'], 'binding case')
    return evaluateExclusiveBinding(item)
  })
  if (canonical(bindingCases.map((item) => item.accepted_mechanism).sort(ordinal)) !== canonical(MECHANISMS)) throw new AssuranceExclusivityError('typed binding cases changed')
  for (const item of context.binding_cases.slice(1)) {
    if (canonical(item.snapshot) !== canonical(context.binding_cases[0].snapshot) || canonical(item.policy) !== canonical(context.binding_cases[0].policy)) {
      throw new AssuranceExclusivityError('binding cases must share one complete portfolio and receiver policy')
    }
  }

  exact(context.forum_case, ['accepted_forum_authority', 'accepted_portfolio', 'commitment', 'reliance_position'], 'forum case')
  const forum = evaluateForumCommitment(context.forum_case)
  if (canonical(context.forum_case.accepted_portfolio) !== canonical(context.binding_cases[0].snapshot)) throw new AssuranceExclusivityError('forum and binding cases do not share the same complete portfolio')

  exact(context.qingdao, ['buyer_a', 'buyer_b', 'combined_snapshot', 'combined_view_possessed_by_buyers', 'declared_case'], 'Qingdao control')
  exact(context.qingdao.declared_case, ['allocation_amount_each', 'capacity_id', 'contract_ids', 'total_capacity', 'unit'], 'Qingdao declaration')
  if (context.qingdao.declared_case.capacity_id !== 'qingdao-capacity-01' || context.qingdao.declared_case.total_capacity !== 1000000 || context.qingdao.declared_case.allocation_amount_each !== 800000 || context.qingdao.declared_case.unit !== 'TEST_USD') throw new AssuranceExclusivityError('Qingdao declared capacity identity or amounts changed')
  if (canonical(context.qingdao.declared_case.contract_ids) !== canonical(['CONTRACT_A', 'CONTRACT_B'])) throw new AssuranceExclusivityError('Qingdao contract identities changed')
  if (context.qingdao.combined_view_possessed_by_buyers !== false) throw new AssuranceExclusivityError('Qingdao control must record that neither buyer possessed the combined view')
  const buyerA = evaluateWitnessedView(context.qingdao.buyer_a)
  const buyerB = evaluateWitnessedView(context.qingdao.buyer_b)
  if (buyerA.witness_operator_id === buyerB.witness_operator_id || buyerA.witness_log_id === buyerB.witness_log_id || context.qingdao.buyer_a.witnessRoot.public_key_spki_b64 === context.qingdao.buyer_b.witnessRoot.public_key_spki_b64) throw new AssuranceExclusivityError('Qingdao control requires distinct witness keys, operators, and log identities')
  const expectedA = { allocation_id: 'qingdao-contract-a', amount: 800000, beneficiary: 'buyer-a', binding_id: 'declared-a', covenant_id: 'CONTRACT_A', encumbered_through: 200 }
  const expectedB = { allocation_id: 'qingdao-contract-b', amount: 800000, beneficiary: 'buyer-b', binding_id: 'declared-b', covenant_id: 'CONTRACT_B', encumbered_through: 200 }
  if (canonical(context.qingdao.buyer_a.snapshot.allocations) !== canonical([expectedA]) || canonical(context.qingdao.buyer_b.snapshot.allocations) !== canonical([expectedB])) {
    throw new AssuranceExclusivityError('Qingdao local allocations do not match the frozen contracts')
  }
  if (context.qingdao.buyer_a.snapshot.capacity_id !== 'qingdao-capacity-01' || context.qingdao.buyer_b.snapshot.capacity_id !== 'qingdao-capacity-01' || context.qingdao.buyer_a.snapshot.total_capacity !== 1000000 || context.qingdao.buyer_b.snapshot.total_capacity !== 1000000 || context.qingdao.buyer_a.snapshot.unit !== 'TEST_USD' || context.qingdao.buyer_b.snapshot.unit !== 'TEST_USD') {
    throw new AssuranceExclusivityError('Qingdao local capacity or unit changed')
  }
  if (context.qingdao.buyer_a.snapshot.challenge_horizon !== 200 || context.qingdao.buyer_b.snapshot.challenge_horizon !== 200) throw new AssuranceExclusivityError('Qingdao local challenge horizon changed')
  if (canonical(context.qingdao.combined_snapshot.allocations) !== canonical([expectedA, expectedB])) throw new AssuranceExclusivityError('Qingdao combined audit is not the exact union of the witnessed local allocations')
  if (context.qingdao.combined_snapshot.capacity_id !== 'qingdao-capacity-01' || context.qingdao.combined_snapshot.total_capacity !== 1000000 || context.qingdao.combined_snapshot.unit !== 'TEST_USD' || context.qingdao.combined_snapshot.challenge_horizon !== 200) throw new AssuranceExclusivityError('Qingdao combined capacity identity, unit, or challenge horizon changed')
  const combined = auditPortfolio(context.qingdao.combined_snapshot, context.qingdao.combined_snapshot.portfolio_root)
  if (buyerA.allocated !== 800000 || buyerB.allocated !== 800000 || combined.allocated !== 1600000 || combined.status !== 'CAPACITY_EXCEEDED') throw new AssuranceExclusivityError('Qingdao split-view result changed')

  return {
    binding_cases: bindingCases,
    constitution: CONSTITUTION,
    external_counter_increment: 0,
    funds_moved: false,
    kernel: context.kernel,
    never_infer: [
      'GLOBAL_FREEDOM_FROM_UNDISCLOSED_CLAIMS',
      'FREEDOM_FROM_CROSS_POLICY_REUSE',
      'SOLVENCY_OR_COLLECTIBILITY',
      'LEGAL_ENFORCEABILITY',
      'PERMANENT_AVAILABILITY',
      'INDEPENDENT_OPERATION',
      'REAL_FUNDS_OR_LIVE_INSTITUTION',
    ],
    profile: 'glyph.assurance-exclusivity-report/0.1-experimental',
    qingdao: {
      buyer_a: buyerA,
      buyer_b: buyerB,
      combined_audit: combined,
      combined_view_possessed_by_buyers: false,
      conclusion: 'TWO_VALID_LOCAL_WITNESSED_VIEWS_DO_NOT_ESTABLISH_EXCLUSIVITY',
    },
    pre_reliance_forum: forum,
    public_protocol: false,
    scope: 'MODEL_ONLY_PROJECT_OPERATED_FIXTURES',
  }
}

export const profiles = Object.freeze({ BINDING_PROFILE, CONSTITUTION, PROFILE, WITNESS_PROFILE })
