"""P42 recovery lab. Python 3.10+ and SQLite, standard library only.

Reopening a connection models a replacement worker. Explicit exceptions mark
failure windows; the experiment does not kill a process or move real money.
Run with: python3 always-on-handoff.py
"""

import sqlite3
from contextlib import ExitStack, closing
from pathlib import Path
from tempfile import TemporaryDirectory


class Interrupted(Exception):
    """Stop at a specified point in the protocol."""


def fire_due_timer(db, now, interrupt=False):
    # UPDATE takes the SQLite write lock. Only the first caller can fire P42's
    # one-shot occurrence. A failed transaction leaves the timer ready again.
    with db:
        changed = db.execute(
            "UPDATE timer SET fired = 1 WHERE id = ? AND due <= ? AND fired = 0",
            ("P42/0915", now),
        ).rowcount
        if changed:
            if interrupt:
                raise Interrupted()
            db.execute("INSERT INTO inbox VALUES ('shop', 'timer', 'P42/0915', 0)")
        return changed


def finish_run(db, epoch, revision, interrupt=False):
    # The lease service has already issued the epoch. A local UPDATE guarded
    # by epoch and revision is the last point at which stale work can be rejected.
    with db:
        changed = db.execute(
            """UPDATE cases SET state = 'notice_due', revision = revision + 1
               WHERE id = 'P42' AND epoch = ? AND revision = ?
               AND state = 'waiting'""",
            (epoch, revision),
        ).rowcount
        if not changed:
            return False
        if interrupt:
            raise Interrupted()
        db.execute("INSERT INTO outbox VALUES ('P42/notice/2', 'pending')")
        db.execute("UPDATE inbox SET done = 1 WHERE source = 'timer' AND event = 'P42/0915'")
        return True


def keyed_delivery(local, remote, lose_ack=False):
    key = "P42/notice/2"
    # One remote insert represents both the visible effect and its dedupe key.
    # Splitting those two writes would introduce another failure window.
    with remote:
        remote.execute("INSERT INTO received VALUES (?) ON CONFLICT(id) DO NOTHING", (key,))
    if lose_ack:
        raise Interrupted()  # Remote committed. Local record still says pending.
    with local:
        local.execute("UPDATE outbox SET state = 'confirmed' WHERE id = ?", (key,))


def run(directory):
    with ExitStack() as resources:
        def connect(name):
            return resources.enter_context(closing(sqlite3.connect(directory / name)))

        first = connect("service.sqlite")
        first.executescript("""
            CREATE TABLE cases (id TEXT PRIMARY KEY, epoch INTEGER, revision INTEGER, state TEXT);
            CREATE TABLE timer (id TEXT PRIMARY KEY, due INTEGER, fired INTEGER);
            CREATE TABLE inbox (tenant TEXT, source TEXT, event TEXT, done INTEGER,
                                PRIMARY KEY (tenant, source, event));
            CREATE TABLE outbox (id TEXT PRIMARY KEY, state TEXT);
            INSERT INTO cases VALUES ('P42', 7, 1, 'waiting');
            INSERT INTO timer VALUES ('P42/0915', 15, 0);
        """)
        with first:
            for _ in range(2):
                first.execute("""INSERT INTO inbox VALUES ('shop', 'carrier', 'delay/42', 0)
                                 ON CONFLICT(tenant, source, event) DO NOTHING""")
        assert first.execute("SELECT count(*) FROM inbox").fetchone() == (1,)
        assert fire_due_timer(first, 14) == 0
        try:
            fire_due_timer(first, 15, interrupt=True)
        except Interrupted:
            pass
        assert first.execute("SELECT fired FROM timer").fetchone() == (0,)
        assert first.execute("SELECT count(*) FROM inbox WHERE source = 'timer'").fetchone() == (0,)

        replacement = connect("service.sqlite")
        assert fire_due_timer(replacement, 15) == 1
        assert fire_due_timer(first, 15) == 0
        with replacement:  # Model successful ownership transfer after lease expiry.
            replacement.execute("UPDATE cases SET epoch = 8 WHERE id = 'P42' AND epoch = 7")
        assert not finish_run(first, epoch=7, revision=1)
        assert not finish_run(replacement, epoch=8, revision=0)
        try:
            finish_run(replacement, epoch=8, revision=1, interrupt=True)
        except Interrupted:
            pass
        assert replacement.execute("SELECT state, revision FROM cases").fetchone() == ("waiting", 1)
        assert replacement.execute("SELECT count(*) FROM outbox").fetchone() == (0,)
        assert replacement.execute("SELECT done FROM inbox WHERE source = 'timer'").fetchone() == (0,)
        assert finish_run(replacement, epoch=8, revision=1)
        assert not finish_run(replacement, epoch=8, revision=1)

        provider = connect("recipient.sqlite")
        provider.executescript("""
            CREATE TABLE received (id TEXT PRIMARY KEY);
            CREATE TABLE ordinary_receipts (case_ref TEXT, receipt TEXT PRIMARY KEY);
        """)
        try:
            keyed_delivery(replacement, provider, lose_ack=True)
        except Interrupted:
            pass
        replacement.close()
        resumed = connect("service.sqlite")
        assert resumed.execute("SELECT state FROM outbox").fetchone() == ("pending",)
        assert provider.execute("SELECT count(*) FROM received").fetchone() == (1,)
        keyed_delivery(resumed, provider)
        assert resumed.execute("SELECT state FROM outbox").fetchone() == ("confirmed",)
        assert provider.execute("SELECT count(*) FROM received").fetchone() == (1,)

        # Alternative channel: an operation reference is searchable but the
        # recipient does not enforce uniqueness on it. A retry could duplicate.
        with resumed:
            resumed.execute("INSERT INTO outbox VALUES ('P42/manual', 'sending')")
        with provider:
            provider.execute("INSERT INTO ordinary_receipts VALUES ('P42/manual', 'receipt-19')")
        # Time out after the provider commits. Stop; no automatic second send.
        with resumed:
            resumed.execute("UPDATE outbox SET state = 'unknown' WHERE id = 'P42/manual'")
        assert resumed.execute("SELECT state FROM outbox WHERE id = 'P42/manual'").fetchone() == ("unknown",)
        # The operator has an authoritative, complete receipt ledger for this
        # fixture. An empty, stale or ambiguous lookup would leave state unknown.
        matches = provider.execute(
            "SELECT receipt FROM ordinary_receipts WHERE case_ref = 'P42/manual'"
        ).fetchall()
        if len(matches) == 1:
            with resumed:
                resumed.execute("UPDATE outbox SET state = 'reconciled' WHERE id = 'P42/manual'")
        assert resumed.execute("SELECT state FROM outbox WHERE id = 'P42/manual'").fetchone() == ("reconciled",)
        print("timer=1 stale_writer=rejected rollback=clean keyed_effects=1 unkeyed=unknown->reconciled")


if __name__ == "__main__":
    with TemporaryDirectory() as temp:
        run(Path(temp))
