export function checkOutcomeReceipt(value) {
  const issues = []
  const fail = message => { issues.push(message) }
  const obj = x => x !== null && typeof x === 'object' && !Array.isArray(x)
  const ref = x => typeof x === 'string' && /^[A-Za-z0-9._:-]{1,100}$/.test(x)
  const minor = x => Number.isSafeInteger(x) && x >= 0 && x <= 1e12
  const states = ['accepted', 'rejected', 'pending']
  const shape = (x, keys, name) => {
    if (!obj(x)) { fail(name + ' must be an object.'); return false }
    if (Object.keys(x).some(key => !keys.includes(key)) || keys.some(key => !Object.hasOwn(x, key))) fail(name + ' has missing or unsupported fields.')
    return true
  }
  if (!shape(value, ['version', 'taskId', 'authorizationRef', 'policyRef', 'criterionRef', 'contract', 'attempts', 'acceptance', 'invoice', 'settlement'], 'Receipt')) return { issues, internallyConsistent: false, totals: null }
  if (value.version !== '0.1') fail('Only draft receipt version 0.1 is supported.')
  for (const key of ['taskId', 'authorizationRef', 'policyRef', 'criterionRef']) if (!ref(value[key])) fail(key + ' must be a nonempty example identifier using letters, digits, dot, colon, underscore or hyphen.')
  const c = value.contract, acceptance = value.acceptance, invoice = value.invoice, settlement = value.settlement
  const contractOk = shape(c, ['currency', 'billingBasis', 'unitPriceMinor', 'retryCostBearer'], 'Contract')
  const acceptanceOk = shape(acceptance, ['status', 'criterionRef', 'attemptId', 'evidenceRef'], 'Acceptance')
  const invoiceOk = shape(invoice, ['totalMinor'], 'Invoice')
  const settlementOk = shape(settlement, ['status', 'amountMinor', 'reference'], 'Settlement')
  if (contractOk) {
    if (c.currency !== 'USD') fail('This draft supports USD minor units only; do not mix currencies or token decimals.')
    if (!['attempt', 'accepted_outcome'].includes(c.billingBasis)) fail('Choose attempt or accepted_outcome billing.')
    if (!minor(c.unitPriceMinor)) fail('Unit price must be a bounded nonnegative integer number of cents.')
    if (!['operator', 'provider', 'buyer', 'unresolved'].includes(c.retryCostBearer)) fail('Retry-cost bearer must be a listed party.')
    if (c.retryCostBearer === 'unresolved') fail('Retry-cost allocation is unresolved.')
  }
  let attemptsOk = Array.isArray(value.attempts) && value.attempts.length >= 1 && value.attempts.length <= 100
  if (!attemptsOk) fail('Provide between 1 and 100 attempts.')
  const ids = new Set(), accepted = []
  let upstreamMinor = 0, buyerBillableCount = 0, pending = 0
  if (attemptsOk) for (const attempt of value.attempts) {
    if (!shape(attempt, ['attemptId', 'authorizationRef', 'policyRef', 'status', 'buyerBillable', 'upstreamCostMinor'], 'Attempt')) { attemptsOk = false; continue }
    if (!ref(attempt.attemptId)) fail('Every attempt needs a bounded identifier.')
    if (ids.has(attempt.attemptId)) fail('Duplicate attempt identifier.')
    ids.add(attempt.attemptId)
    if (attempt.authorizationRef !== value.authorizationRef || attempt.policyRef !== value.policyRef) fail('Attempt authority references differ from the task record.')
    if (!states.includes(attempt.status)) fail('Attempt status must be accepted, rejected or pending.')
    if (typeof attempt.buyerBillable !== 'boolean') fail('buyerBillable must be a boolean, not a string or number.')
    if (!minor(attempt.upstreamCostMinor)) { fail('Upstream attempt costs must be bounded nonnegative integer cents.'); attemptsOk = false }
    else upstreamMinor += attempt.upstreamCostMinor
    if (attempt.buyerBillable === true) buyerBillableCount++
    if (attempt.status === 'accepted') accepted.push(attempt)
    if (attempt.status === 'pending') pending++
  }
  if (accepted.length > 1) fail('This draft supports one accepted outcome per task.')
  if (acceptanceOk) {
    if (!states.includes(acceptance.status)) fail('Acceptance status must be accepted, rejected or pending.')
    if (acceptance.criterionRef !== value.criterionRef) fail('Acceptance criterion differs from the task criterion.')
    if (acceptance.evidenceRef !== null && !ref(acceptance.evidenceRef)) fail('Acceptance evidence reference must be a bounded identifier or null.')
    if (acceptance.status === 'accepted') {
      if (!ref(acceptance.evidenceRef)) fail('Accepted work needs an evidence reference; its truth still requires external verification.')
      if (!ref(acceptance.attemptId) || accepted.length !== 1 || accepted[0]?.attemptId !== acceptance.attemptId) fail('Accepted outcome does not identify exactly one accepted attempt.')
      if (pending) fail('Resolve pending attempts before marking this task accepted in this draft.')
    } else {
      if (accepted.length) fail('An attempt is accepted while task acceptance is not accepted.')
      if (acceptance.attemptId !== null) fail('Nonaccepted task records must use a null accepted-attempt reference.')
      if (acceptance.status === 'rejected' && pending) fail('A final rejected task still contains pending attempts.')
    }
  }
  if (invoiceOk && !minor(invoice.totalMinor)) fail('Invoice total must be bounded nonnegative integer cents.')
  if (settlementOk) {
    if (!['pending', 'settled', 'disputed'].includes(settlement.status)) fail('Choose a listed settlement status.')
    if (!minor(settlement.amountMinor)) fail('Settlement amount must be bounded nonnegative integer cents.')
    if (settlement.reference !== null && !ref(settlement.reference)) fail('Settlement reference must be a bounded identifier or null.')
    if (settlement.status === 'settled') {
      if (!ref(settlement.reference)) fail('Settled payment needs a reference; the checker does not look it up.')
      if (invoiceOk && settlement.amountMinor !== invoice.totalMinor) fail('Settled amount differs from the invoice total.')
    } else if (settlement.status === 'pending' && settlement.amountMinor !== 0) fail('This draft records pending settlement as zero settled cents.')
    if (settlement.status === 'disputed') fail('Payment is disputed; reconcile outside this draft before closing the record.')
  }
  let totals = null
  if (attemptsOk && contractOk && minor(c.unitPriceMinor) && acceptanceOk && ['attempt', 'accepted_outcome'].includes(c.billingBasis)) {
    const units = c.billingBasis === 'attempt' ? buyerBillableCount : (acceptance.status === 'accepted' ? 1 : 0)
    const expectedInvoiceMinor = units * c.unitPriceMinor
    if (invoiceOk && invoice.totalMinor !== expectedInvoiceMinor) fail('Invoice total differs from the declared billing rule.')
    totals = { upstreamMinor, expectedInvoiceMinor, buyerBillableCount, acceptedOutcomes: acceptance.status === 'accepted' ? 1 : 0 }
  }
  return { issues: [...new Set(issues)], internallyConsistent: issues.length === 0, totals }
}

