"""A local failure illustration, not a payment SDK. Python standard library only.
Run: python3 example.py
Two SQLite files simulate an application ledger and an external service. No
network, provider, model or payment calls. The fake service deliberately expires
its response cache but retains queryable effect receipts. These are assumptions,
not claims about Stripe or any other provider. Time is an explicit integer.
"""
import concurrent.futures
import hashlib
import json
import pathlib
import sqlite3
import tempfile


class Conflict(Exception):
    pass


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


class Service:
    def __init__(self, path):
        self.path = str(path)
        with self.db() as db:
            db.executescript('''
                CREATE TABLE effects(receipt INTEGER PRIMARY KEY AUTOINCREMENT,
                  tenant TEXT, operation TEXT, action TEXT, fingerprint TEXT);
                CREATE TABLE cache(tenant TEXT, operation TEXT, key TEXT,
                  fingerprint TEXT, receipt INTEGER, expires INTEGER,
                  PRIMARY KEY(tenant, operation, key));
            ''')

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

    def execute(self, tenant, operation, key, action, payload, now, lose_response=False):
        fingerprint = digest(payload)
        with self.db() as db:
            db.execute('BEGIN IMMEDIATE')
            previous = db.execute('SELECT fingerprint, receipt, expires FROM cache WHERE tenant=? AND operation=? AND key=?', (tenant, operation, key)).fetchone()
            if previous and previous[2] > now:
                if previous[0] != fingerprint:
                    raise Conflict('service payload mismatch')
                receipt = previous[1]
            else:
                receipt = db.execute('INSERT INTO effects(tenant, operation, action, fingerprint) VALUES (?,?,?,?)', (tenant, operation, action, fingerprint)).lastrowid
                db.execute('INSERT OR REPLACE INTO cache VALUES(?,?,?,?,?,?)', (tenant, operation, key, fingerprint, receipt, now+60))
        # The remote transaction has committed before this simulated timeout.
        if lose_response:
            raise TimeoutError('response lost after effect committed')
        return receipt

    def lookup(self, tenant, operation, action):
        with self.db() as db:
            return db.execute('SELECT receipt, fingerprint FROM effects WHERE tenant=? AND operation=? AND action=?', (tenant, operation, action)).fetchall()

    def count(self):
        with self.db() as db:
            return db.execute('SELECT COUNT(*) FROM effects').fetchone()[0]


class Client:
    def __init__(self, path, service):
        self.path, self.service = str(path), service
        with self.db() as db:
            db.execute('''CREATE TABLE IF NOT EXISTS actions(tenant TEXT, operation TEXT, action TEXT,
              fingerprint TEXT, key TEXT, state TEXT, receipt INTEGER,
              PRIMARY KEY(tenant, operation, action))''')

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

    def submit(self, tenant, operation, action, payload, now, lose_response=False, stop_before_send=False):
        identity = (tenant, operation, action)
        fingerprint = digest(payload)
        # Stable logical identity is stored before the effect can happen.
        key = digest(list(identity))
        with self.db() as db:
            db.execute('BEGIN IMMEDIATE')
            row = db.execute('SELECT fingerprint, state, receipt FROM actions WHERE tenant=? AND operation=? AND action=?', identity).fetchone()
            if row:
                if row[0] != fingerprint:
                    raise Conflict('client payload mismatch')
                return {'state':row[1], 'receipt':row[2]}
            db.execute('INSERT INTO actions VALUES(?,?,?,?,?,?,NULL)', (*identity, fingerprint, key, 'pending'))
        try:
            if stop_before_send:
                raise TimeoutError('fixture stopped before transmission')
            receipt = self.service.execute(tenant, operation, key, action, payload, now, lose_response)
        except TimeoutError:
            with self.db() as db:
                db.execute("UPDATE actions SET state='unknown' WHERE tenant=? AND operation=? AND action=?", identity)
            return {'state':'unknown', 'receipt':None}
        with self.db() as db:
            db.execute("UPDATE actions SET state='succeeded', receipt=? WHERE tenant=? AND operation=? AND action=?", (receipt, *identity))
        return {'state':'succeeded','receipt':receipt}

    def reconcile(self, tenant, operation, action):
        identity = (tenant, operation, action)
        with self.db() as db:
            row = db.execute('SELECT fingerprint, state, receipt FROM actions WHERE tenant=? AND operation=? AND action=?', identity).fetchone()
        if row is None:
            raise KeyError(identity)
        if row[1] == 'succeeded':
            return {'state':'succeeded','receipt':row[2]}
        matches = self.service.lookup(*identity)
        # A missing or ambiguous lookup is not permission to execute again.
        if not matches:
            return {'state':row[1],'receipt':None}
        if len(matches) != 1 or matches[0][1] != row[0]:
            raise Conflict('manual reconciliation required')
        with self.db() as db:
            db.execute("UPDATE actions SET state='succeeded', receipt=? WHERE tenant=? AND operation=? AND action=?", (matches[0][0], *identity))
        return {'state':'succeeded','receipt':matches[0][0]}


def must_conflict(call, message):
    try:
        call()
    except Conflict as exc:
        assert str(exc) == message
    else:
        raise AssertionError('mismatch accepted')


def main():
    payload = {'amount_units':2500, 'currency':'UNIT', 'destination':'fixture-vendor'}
    with tempfile.TemporaryDirectory() as directory:
        directory = pathlib.Path(directory)
        service = Service(directory/'service.db')
        client = Client(directory/'client.db', service)
        first = client.submit('tenant-a','purchase','order-17',payload,0,lose_response=True)
        assert first['state'] == 'unknown' and service.count() == 1
        # Reopen application object to show stored identity survives its restart.
        client = Client(directory/'client.db', service)
        repeats = [client.submit('tenant-a','purchase','order-17',payload,10+i) for i in range(10)]
        assert all(x['state']=='unknown' for x in repeats) and service.count()==1
        must_conflict(lambda:client.submit('tenant-a','purchase','order-17',dict(payload,amount_units=2600),20),'client payload mismatch')
        reconciled = client.reconcile('tenant-a','purchase','order-17')
        assert reconciled == {'state':'succeeded','receipt':1}
        late = client.submit('tenant-a','purchase','order-17',payload,1000)
        assert late == reconciled and service.count() == 1
        absent = client.submit('tenant-a','purchase','order-absent',payload,1000,stop_before_send=True)
        assert absent['state']=='unknown'
        assert client.reconcile('tenant-a','purchase','order-absent')['state']=='unknown'
        assert service.count()==1
        # Same textual key in a different tenant is a distinct authorized scope.
        service.execute('tenant-b','purchase',digest(['tenant-a','purchase','order-17']),'other-order',payload,1)
        assert service.count()==2
        # Thirty concurrent submissions of one new logical action add one effect.
        with concurrent.futures.ThreadPoolExecutor(max_workers=30) as pool:
            list(pool.map(lambda _: client.submit('tenant-a','purchase','concurrent',payload,1001), range(30)))
        assert service.count()==3
        assert client.reconcile('tenant-a','purchase','concurrent')['state']=='succeeded'
        # Separate counterexample: relying only on a 60-unit response cache.
        naive = Service(directory/'naive.db')
        naive.execute('tenant-a','purchase','same-key','same-action',payload,0)
        naive.execute('tenant-a','purchase','same-key','same-action',payload,1)
        assert naive.count()==1
        must_conflict(lambda:naive.execute('tenant-a','purchase','same-key','same-action',dict(payload,amount_units=2600),2),'service payload mismatch')
        naive.execute('tenant-a','purchase','same-key','same-action',payload,61)
        assert naive.count()==2
        result = {'kind':'local simulated service with deliberately finite response cache; no provider or payment calls',
          'lost_response_action':{'initial_state':'unknown','repeated_submissions':10,'effects_before_reconciliation':1,
                                 'after_reconciliation':'succeeded','late_submission_time':1000,'effects_after_late_submission':1},
          'changed_payload':'rejected','restart_preserved_identity':True,'missing_lookup':'remains unknown',
          'distinct_tenant':'distinct effect','concurrent_submissions':30,'concurrent_action_effects':1,
          'naive_cache_only':{'cache_window':60,'effects_before_expiry':1,'effects_after_expiry':2},
          'limits':['Fixture service retains authoritative searchable receipts indefinitely','No real API retention guarantees tested',
                    'Unknown actions intentionally sacrifice automatic progress','Single local database per component; no distributed failover testing',
                    'No real money and no current provider performance measurement']}
    pathlib.Path(__file__).with_name('result.json').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps(result,indent=2))


if __name__ == '__main__':
    main()
