#!/usr/bin/env python3
"""Runbook Draft original educational sample. No HTTP endpoint or real payments.
Run: python3 webhook-ledger.py
Requires Python 3.9+ with sqlite3 and SQLite 3.24+.
"""
import concurrent.futures
import os
import sqlite3
import subprocess
import sys
import tempfile


def apply_event(path, tenant, event_id, units, fail=False):
    if not tenant or not event_id or type(units) is not int or units <= 0:
        raise ValueError('Expected a tenant, stable event ID, and positive integer units')
    db = sqlite3.connect(path, isolation_level=None, timeout=10)
    try:
        db.execute('BEGIN IMMEDIATE')
        inserted = db.execute(
            'INSERT INTO received(tenant, event_id) VALUES (?, ?) '
            'ON CONFLICT(tenant, event_id) DO NOTHING', (tenant, event_id)
        ).rowcount
        if not inserted:
            db.execute('COMMIT')
            return 'duplicate'
        db.execute('INSERT INTO effects(tenant, units) VALUES (?, ?)', (tenant, units))
        if fail:
            raise RuntimeError('Simulated failure before commit')
        db.execute('COMMIT')
        return 'applied'
    except BaseException:
        if db.in_transaction:
            db.execute('ROLLBACK')
        raise
    finally:
        db.close()


def run_demo():
    with tempfile.TemporaryDirectory() as directory:
        path = os.path.join(directory, 'ledger.sqlite')
        with sqlite3.connect(path) as db:
            db.executescript('''
                CREATE TABLE received(
                    tenant TEXT NOT NULL,
                    event_id TEXT NOT NULL,
                    PRIMARY KEY(tenant, event_id)
                );
                CREATE TABLE effects(tenant TEXT NOT NULL, units INTEGER NOT NULL);
            ''')
        assert apply_event(path, 'shop-a', 'evt-1', 10) == 'applied'
        assert apply_event(path, 'shop-a', 'evt-1', 10) == 'duplicate'
        print('PASS: repeated delivery changes the database once')
        # A separate Python interpreter reopens the persisted file.
        def worker(event_id):
            return subprocess.check_output(
                [sys.executable, __file__, 'worker', path, event_id], text=True
            ).strip()
        assert worker('evt-1') == 'duplicate'
        print('PASS: a fresh process recognizes a previously committed event')
        try:
            apply_event(path, 'shop-a', 'evt-2', 10, fail=True)
        except RuntimeError:
            pass
        else:
            raise AssertionError('Expected injected failure')
        with sqlite3.connect(path) as db:
            assert db.execute("SELECT COUNT(*) FROM received WHERE event_id='evt-2'").fetchone()[0] == 0
            assert db.execute('SELECT COUNT(*) FROM effects').fetchone()[0] == 1
        assert apply_event(path, 'shop-a', 'evt-2', 10) == 'applied'
        print('PASS: rollback removes both marker and effect; retry can succeed')
        assert apply_event(path, 'shop-b', 'evt-1', 10) == 'applied'
        print('PASS: distinct tenant identities are independent')
        with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
            results = list(pool.map(worker, ['evt-3'] * 6))
        assert results.count('applied') == 1 and results.count('duplicate') == 5
        with sqlite3.connect(path) as db:
            assert db.execute('SELECT COUNT(*), SUM(units) FROM effects').fetchone() == (4, 40)
        print('PASS: six concurrent processes produce one new effect')
        print('Scope: local SQLite effects only; no HTTP, signature verification, gateway, external API, or power-loss test.')
        print('Runtime: Python ' + sys.version.split()[0] + '; SQLite ' + sqlite3.sqlite_version)


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == 'worker':
        print(apply_event(sys.argv[2], 'shop-a', sys.argv[3], 10))
    else:
        run_demo()
