const retrySequences = {
  "serial": {
    "label": "Serial retry after completion",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "overlap": {
    "label": "Two arrivals before completion",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "lost-response": {
    "label": "Effect occurs; completion record is lost",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "lose",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "expired-cache": {
    "label": "Response cache expires before retry",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "expire"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "changed-payload": {
    "label": "Same key; changed destination",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-b",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "regenerated-key": {
    "label": "Same logical operation; newly generated key",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-2",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "different-principal": {
    "label": "Same key label; two different principals",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-b",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  },
  "different-operation": {
    "label": "Same key reused for a different logical operation",
    "events": [
      {
        "type": "arrive",
        "requestId": "r1",
        "principal": "buyer-a",
        "operationId": "operation-1",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r1"
      },
      {
        "type": "arrive",
        "requestId": "r2",
        "principal": "buyer-a",
        "operationId": "operation-2",
        "key": "payment-key-1",
        "destination": "merchant-a",
        "amountMinor": 100,
        "asset": "USD"
      },
      {
        "type": "complete",
        "requestId": "r2"
      }
    ]
  }
}

export function simulateAgentRetry(scenarioId, design) {
  if (typeof scenarioId !== 'string' || !Object.hasOwn(retrySequences, scenarioId) || !['cache', 'ledger'].includes(design)) throw new Error('Choose a listed scenario and design model.')
  const cache = new Map(), ledger = new Map(), keyBindings = new Map(), active = new Map(), effectsByOperation = new Map()
  const result = { scenarioId, design, effects: 0, duplicateEffects: 0, distinctOperations: 0, replays: 0, conflicts: 0, inflightBlocks: 0, unknownBlocks: 0, trace: [] }
  const log = message => result.trace.push(message)
  for (const event of retrySequences[scenarioId].events) {
    if (event.type === 'expire') { cache.clear(); log('Response cache expired. Ledger records and key bindings, if used, remain retained by assumption.'); continue }
    if (event.type === 'complete' || event.type === 'lose') {
      const record = active.get(event.requestId)
      if (!record) { log(event.requestId + ': no new execution to complete; arrival was replayed, blocked or rejected.'); continue }
      if (event.type === 'lose') {
        if (design === 'ledger') ledger.get(record.operationKey).state = 'unknown'
        log(event.requestId + ': abstract effect already occurred; no completed-response record was stored.')
      } else {
        if (design === 'cache') cache.set(record.paymentKey, { fingerprint: record.fingerprint })
        else ledger.get(record.operationKey).state = 'complete'
        log(event.requestId + ': completion recorded.')
      }
      active.delete(event.requestId); continue
    }
    const paymentKey = JSON.stringify([event.principal, event.key])
    const operationKey = JSON.stringify([event.principal, event.operationId])
    const fingerprint = JSON.stringify([event.operationId, event.destination, event.amountMinor, event.asset])
    if (design === 'cache') {
      const previous = cache.get(paymentKey)
      if (previous) {
        if (previous.fingerprint !== fingerprint) { result.conflicts++; log(event.requestId + ': fingerprint conflict; no new effect.'); continue }
        result.replays++; log(event.requestId + ': completed result replayed; no new effect.'); continue
      }
    } else {
      const binding = keyBindings.get(paymentKey)
      if (binding && binding !== fingerprint) { result.conflicts++; log(event.requestId + ': payment key conflicts with its retained fingerprint; no new effect.'); continue }
      const previous = ledger.get(operationKey)
      if (previous) {
        if (previous.fingerprint !== fingerprint) { result.conflicts++; log(event.requestId + ': logical-operation fingerprint conflict; no new effect.'); continue }
        keyBindings.set(paymentKey, fingerprint)
        if (previous.state === 'complete') { result.replays++; log(event.requestId + ': retained logical-operation result replayed; no new effect.') }
        else if (previous.state === 'unknown') { result.unknownBlocks++; log(event.requestId + ': prior effect is unresolved; stop and reconcile externally.') }
        else { result.inflightBlocks++; log(event.requestId + ': logical operation is in flight; no second effect admitted.') }
        continue
      }
      keyBindings.set(paymentKey, fingerprint)
      ledger.set(operationKey, { fingerprint, state: 'inflight' })
      log(event.requestId + ': logical operation reserved atomically before the effect, by model assumption.')
    }
    result.effects++
    const count = (effectsByOperation.get(operationKey) || 0) + 1
    effectsByOperation.set(operationKey, count)
    if (count > 1) result.duplicateEffects++
    active.set(event.requestId, { operationKey, paymentKey, fingerprint })
    log(event.requestId + ': abstract effect committed for ' + event.principal + ' / ' + event.operationId + '.')
  }
  result.distinctOperations = effectsByOperation.size
  return result
}
