"""Private SQLite range allocator with two independent child processes.

No external database. Every run creates and removes its own temporary directory.
Children start together; output sorts by allocated range, not scheduling order.
Commit/read-back and a suppressed return are tested, not power-loss durability.
"""
import multiprocessing as mp
from pathlib import Path
import sqlite3
import tempfile


def connect(path):
    db = sqlite3.connect(path, timeout=10, isolation_level=None)
    db.execute("pragma synchronous=EXTRA")
    return db


def reserve(db, count, commit=True):
    if type(count) is not int or count <= 0:
        raise ValueError("count must be a positive integer")
    db.execute("begin immediate")
    try:
        old = db.execute("select high from allocator where name='objects'").fetchone()[0]
        if old + count > 2**63 - 1:
            raise OverflowError("ticket space exhausted")
        db.execute("update allocator set high=? where name='objects'", (old + count,))
        db.execute("commit" if commit else "rollback")
        return old + 1, old + count
    except BaseException:
        if db.in_transaction:
            db.execute("rollback")
        raise


def child(path, start, result):
    db = connect(path)
    start.wait()
    low, high = reserve(db, 3)
    # Use only the first ticket, then end this worker with the rest unused.
    db.execute("insert into objects values (?)", (low,))
    db.close()
    result.send((low, high))
    result.close()


def main():
    with tempfile.TemporaryDirectory(prefix="fanout-m09-tickets-") as directory:
        path = str(Path(directory) / "tickets.sqlite")
        db = connect(path)
        db.executescript("create table allocator(name text primary key, high integer not null);"
                         "insert into allocator values ('objects', 0);"
                         "create table objects(id integer primary key);")
        ctx = mp.get_context("spawn")
        start = ctx.Event()
        workers, pipes = [], []
        for _ in range(2):
            receive, send = ctx.Pipe(duplex=False)
            process = ctx.Process(target=child, args=(path, start, send))
            process.start()
            send.close()
            workers.append(process)
            pipes.append(receive)
        start.set()
        ranges = []
        for pipe in pipes:
            if not pipe.poll(15):
                raise RuntimeError("child allocation timed out")
            ranges.append(pipe.recv())
            pipe.close()
        for process in workers:
            process.join(15)
            if process.is_alive():
                process.terminate()
                process.join()
                raise RuntimeError("child did not stop")
            assert process.exitcode == 0
        assert len({p.pid for p in workers}) == 2
        print("independent worker processes: 2")
        print("committed ranges:", "; ".join(f"{lo}..{hi}" for lo, hi in sorted(ranges)))
        print("stored objects:", ", ".join(str(r[0]) for r in db.execute("select id from objects order by id")))
        hidden = reserve(db, 3)  # Commit succeeds; fixture suppresses the caller's reply.
        print(f"committed range with suppressed return: {hidden[0]}..{hidden[1]}")
        next_range = reserve(db, 3)
        print(f"next reservation: {next_range[0]}..{next_range[1]}")
        aborted = reserve(db, 3, commit=False)
        print(f"rolled-back candidate, never issued: {aborted[0]}..{aborted[1]}")
        last = reserve(db, 3)
        print(f"next committed reservation: {last[0]}..{last[1]}")
        db.close()
        reopened = connect(path)
        print("high-water mark after reconnect:", reopened.execute("select high from allocator").fetchone()[0])
        reopened.close()


if __name__ == "__main__":
    main()
