"""Local illustration, not a payment implementation. Python standard library only.
Run: python3 example.py
No network or model calls. SQLite serializes writers on one local file.
Trusted application identities, approval UI, provider enforcement and distributed
failover are deliberately out of scope. Amounts are fictional integer units.
"""
import concurrent.futures
import hashlib
import json
import pathlib
import sqlite3
import tempfile
import threading


class Rejected(Exception):
    pass


def fingerprint(action):
    return hashlib.sha256(json.dumps(action, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


class Ledger:
    def __init__(self, path, limit=10000):
        self.path = str(path)
        with self.db() as db:
            db.executescript("""
                CREATE TABLE wallet (id INTEGER PRIMARY KEY, ceiling INTEGER NOT NULL);
                CREATE TABLE approvals (operation TEXT PRIMARY KEY, digest TEXT NOT NULL);
                CREATE TABLE operations (
                    operation TEXT PRIMARY KEY, digest TEXT NOT NULL,
                    reserved INTEGER NOT NULL CHECK(reserved >= 0),
                    spent INTEGER NOT NULL DEFAULT 0 CHECK(spent >= 0),
                    state TEXT NOT NULL);
            """)
            db.execute("INSERT INTO wallet VALUES(1, ?)", (limit,))

    def db(self):
        return sqlite3.connect(self.path, timeout=20)

    def approve(self, action):
        # Trusted reviewer fixture, never exposed as an agent tool.
        with self.db() as db:
            db.execute("INSERT INTO approvals VALUES (?, ?)", (action['operation'], fingerprint(action)))

    def reserve(self, action):
        if action['vendor'] != 'approved-demo' or action['tool'] != 'purchase_fixture' or action['currency'] != 'UNIT':
            raise Rejected('scope')
        amount = action['maximum']
        if type(amount) is not int or not 0 < amount <= 5000:
            raise Rejected('amount')
        digest = fingerprint(action)
        with self.db() as db:
            db.execute('BEGIN IMMEDIATE')
            prior = db.execute('SELECT digest, state FROM operations WHERE operation=?', (action['operation'],)).fetchone()
            if prior:
                if prior[0] != digest:
                    raise Rejected('payload conflict')
                return 'existing:' + prior[1]
            if amount > 2000:
                approved = db.execute('SELECT digest FROM approvals WHERE operation=?', (action['operation'],)).fetchone()
                if not approved or approved[0] != digest:
                    raise Rejected('approval')
            used = db.execute('SELECT COALESCE(SUM(reserved + spent), 0) FROM operations').fetchone()[0]
            ceiling = db.execute('SELECT ceiling FROM wallet WHERE id=1').fetchone()[0]
            if used + amount > ceiling:
                raise Rejected('budget')
            db.execute('INSERT INTO operations VALUES (?, ?, ?, 0, ?)', (action['operation'], digest, amount, 'reserved'))
            return 'reserved'

    def dispatch(self, operation):
        with self.db() as db:
            changed = db.execute("UPDATE operations SET state='sent' WHERE operation=? AND state='reserved'", (operation,)).rowcount
            if changed != 1:
                raise Rejected('dispatch state')

    def unknown(self, operation):
        with self.db() as db:
            changed = db.execute("UPDATE operations SET state='unknown' WHERE operation=? AND state='sent'", (operation,)).rowcount
            if changed != 1:
                raise Rejected('unknown state')

    def settle(self, operation, actual):
        with self.db() as db:
            db.execute('BEGIN IMMEDIATE')
            row = db.execute('SELECT reserved, state FROM operations WHERE operation=?', (operation,)).fetchone()
            if not row or row[1] not in ('sent', 'unknown') or type(actual) is not int or not 0 <= actual <= row[0]:
                raise Rejected('settlement')
            db.execute("UPDATE operations SET reserved=0, spent=?, state='settled' WHERE operation=?", (actual, operation))

    def snapshot(self):
        with self.db() as db:
            reserved, spent = db.execute('SELECT COALESCE(SUM(reserved),0), COALESCE(SUM(spent),0) FROM operations').fetchone()
            ceiling = db.execute('SELECT ceiling FROM wallet').fetchone()[0]
            return {'ceiling': ceiling, 'reserved': reserved, 'spent': spent, 'available': ceiling-reserved-spent}


def action(operation, maximum=700):
    return dict(operation=operation, maximum=maximum, vendor='approved-demo', tool='purchase_fixture', currency='UNIT')


def rejected(call, reason):
    try:
        call()
    except Rejected as exc:
        assert str(exc) == reason, (str(exc), reason)
    else:
        raise AssertionError('request unexpectedly accepted')


def main():
    rounds = []
    with tempfile.TemporaryDirectory() as directory:
        for iteration in range(20):
            ledger = Ledger(pathlib.Path(directory) / f'concurrent-{iteration}.db')
            barrier = threading.Barrier(20)
            def attempt(i):
                barrier.wait()
                try:
                    return i, ledger.reserve(action(str(i)))
                except Rejected as exc:
                    return i, str(exc)
            with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
                outcomes = list(pool.map(attempt, range(20)))
            accepted = [i for i, result in outcomes if result == 'reserved']
            assert len(accepted) == 14
            assert sum(result == 'budget' for _, result in outcomes) == 6
            assert ledger.snapshot() == dict(ceiling=10000, reserved=9800, spent=0, available=200)
            assert ledger.reserve(action(str(accepted[0]))) == 'existing:reserved'
            assert ledger.snapshot()['reserved'] == 9800
            for i in accepted[:10]:
                ledger.dispatch(str(i)); ledger.settle(str(i), 500)
            for i in accepted[10:]:
                ledger.dispatch(str(i)); ledger.unknown(str(i))
            assert ledger.snapshot() == dict(ceiling=10000, reserved=2800, spent=5000, available=2200)
            rejected(lambda: ledger.settle(str(accepted[10]), 701), 'settlement')
            rounds.append({'accepted': 14, 'budget_denied': 6, 'peak_reserved': 9800, 'after_settlement': ledger.snapshot()})
        approvals = Ledger(pathlib.Path(directory) / 'approval.db')
        proposal = action('reviewed-order', 4000)
        rejected(lambda: approvals.reserve(proposal), 'approval')
        approvals.approve(proposal)
        rejected(lambda: approvals.reserve(dict(proposal, maximum=4100)), 'approval')
        assert approvals.reserve(proposal) == 'reserved'
        rejected(lambda: approvals.reserve(dict(proposal, maximum=3900)), 'payload conflict')
        rejected(lambda: approvals.reserve(dict(action('wrong-vendor'), vendor='other')), 'scope')
        rejected(lambda: approvals.reserve(dict(action('negative'), maximum=-1)), 'amount')
        assert approvals.snapshot()['reserved'] == 4000
        result = {'kind':'local deterministic illustration with concurrent scheduling; no payment, provider or model calls',
                  'rounds':20,'concurrent_requests_per_round':20,'request_units':700,'ceiling_units':10000,
                  'total_requests':400,'accepted_total':280,'budget_denied_total':120,
                  'peak_reserved_units_each_round':9800,'overspend_events':0,
                  'last_round':rounds[-1], 'approval_binding':'passed', 'duplicate_reservation':'passed',
                  'scope_validation':'passed','invalid_amount':'passed','over_reservation_settlement':'rejected',
                  'unknown_outcomes_keep_reservations':True,
                  'limits':['One local SQLite database; no distributed failover test','Trusted identity and reviewer are fixture assumptions','No external executor or real currency','Finite test cases do not prove all schedules']}
    destination = pathlib.Path(__file__).with_name('result.json')
    destination.write_text(json.dumps(result, indent=2)+'\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
