"""Offline policy-and-receipt simulator, Python 3.10+, standard library only.
Not production IAM, a payment API, or a cryptographic audit implementation.
The caller is trusted test code. Untrusted model output supplies Action only.
"""
from dataclasses import dataclass, replace
from hashlib import sha256
import json

@dataclass(frozen=True)
class Action:
    tenant: str
    invoice: str
    revision: int
    payee: str
    cents: int
    operation: str = 'pay'

@dataclass(frozen=True)
class Grant:
    user: str
    tenant: str
    audience: str
    invoice: str
    max_cents: int
    expires: int
    revision: int


def digest(action):
    return sha256(json.dumps(action.__dict__, sort_keys=True,
                             separators=(',', ':')).encode()).hexdigest()

class Ledger:
    def __init__(self):
        self.commits = {}  # durable and transactional in a real implementation
        self.events = []
        self.revoked = set()
        self.audit_available = True
        self.invoice_revision = 4

    def execute(self, action, grant, approval, key, now):
        """approval is a trusted approval-service record, not model text.
        Single-threaded transaction simulation; no exactly-once network claim.
        """
        reason = None
        if grant.user in self.revoked: reason = 'revoked'
        elif now >= grant.expires: reason = 'expired'
        elif grant.audience != 'ledger': reason = 'audience'
        elif action.tenant != grant.tenant: reason = 'tenant'
        elif action.invoice != grant.invoice: reason = 'resource'
        elif action.operation != 'pay': reason = 'operation'
        elif type(action.cents) is not int or not 0 < action.cents <= grant.max_cents: reason = 'amount'
        elif action.revision != self.invoice_revision or grant.revision != self.invoice_revision: reason = 'stale_revision'
        elif approval != digest(action): reason = 'approval_binding'
        elif not self.audit_available: reason = 'audit_unavailable'
        elif key in self.commits:
            if self.commits[key]['digest'] != digest(action): reason = 'idempotency_conflict'
            else: return self.commits[key]  # same receipt, no second write
        if reason is None and any(r['invoice'] == action.invoice and r['tenant'] == action.tenant for r in self.commits.values()):
            reason = 'already_settled'
        if reason:
            self.events.append({'state': 'denied', 'reason': reason})
            return {'state': 'denied', 'reason': reason}
        receipt = {'state': 'committed', 'digest': digest(action), 'key': key,
                   'actor': grant.user, 'tenant': grant.tenant,
                   'invoice': action.invoice, 'revision': action.revision, 'policy': 'teaching-v1'}
        # In production: commit effect and durable audit/outbox atomically,
        # or use downstream idempotency + reconciliation; this is in-memory.
        self.commits[key] = receipt
        self.events.append(dict(receipt))
        return receipt


action = Action('tenant-a', 'inv-7', 4, 'supplier-42', 5000)
grant = Grant('user-1', 'tenant-a', 'ledger', 'inv-7', 10000, 100, 4)
approval = digest(action)
ledger = Ledger()
assert ledger.execute(action, grant, approval, 'op-1', 50)['state'] == 'committed'
assert ledger.execute(action, grant, approval, 'op-1', 51)['state'] == 'committed'
assert len(ledger.commits) == 1
assert ledger.execute(action, grant, approval, 'different-key', 51)['reason'] == 'already_settled'
assert ledger.execute(replace(action, tenant='tenant-b'), grant, approval, 'op-2', 50)['reason'] == 'tenant'
assert ledger.execute(replace(action, payee='attacker'), grant, approval, 'op-2', 50)['reason'] == 'approval_binding'
assert ledger.execute(replace(action, cents=10001), grant, approval, 'op-2', 50)['reason'] == 'amount'
assert ledger.execute(action, replace(grant, audience='search'), approval, 'op-2', 50)['reason'] == 'audience'
assert ledger.execute(action, grant, approval, 'op-2', 100)['reason'] == 'expired'
ledger.invoice_revision = 5
assert ledger.execute(action, grant, approval, 'op-2', 50)['reason'] == 'stale_revision'
ledger.invoice_revision = 4
ledger.audit_available = False
assert ledger.execute(action, grant, approval, 'op-2', 50)['reason'] == 'audit_unavailable'
ledger.audit_available = True
ledger.revoked.add('user-1')
assert ledger.execute(action, grant, approval, 'op-2', 50)['reason'] == 'revoked'
assert len(ledger.commits) == 1
print('13 checks passed: approval, tenant, audience, budget, revision, expiry, audit, revocation and replay.')
print('One committed effect. Model-proposed changes cannot expand the trusted grant.')
