#!/usr/bin/env python3
"""Gateway reservation concurrency lab. Python 3.11+, standard library only.

Actual SQLite transactions over a disposable shared file. Unsafe and atomic use
2 worker threads, each with its own connection and a synchronized initial read.
Rollback is explicitly sequential. Tokens are supplied fixture amounts, not
model inference, usage measurements, currency or a production capacity claim.
No external network, credentials, authentication or production database.
"""
import argparse
from contextlib import closing
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time

BUDGET_TOKENS = 1500
RESERVATION_TOKENS = 1000  # In a separate copy, change only this to 700.
TENANT = "north"
CASES = ("unsafe", "atomic", "rollback")
SQLITE_BUSY_SECONDS = 2
BARRIER_SECONDS = 3
WORKER_SECONDS = 6
PROCESS_SECONDS = 10


def connect(path):
    db = sqlite3.connect(path, timeout=SQLITE_BUSY_SECONDS, isolation_level=None)
    db.row_factory = sqlite3.Row
    db.execute("PRAGMA foreign_keys = ON")
    return db


def initialize(path):
    with closing(connect(path)) as db:
        db.executescript("""
            CREATE TABLE budgets (
                tenant_id TEXT PRIMARY KEY, budget_tokens INTEGER NOT NULL,
                remaining_tokens INTEGER NOT NULL);
            CREATE TABLE reservations (
                request_id TEXT PRIMARY KEY,
                tenant_id TEXT NOT NULL REFERENCES budgets(tenant_id),
                amount_tokens INTEGER NOT NULL CHECK(amount_tokens > 0),
                worker_id TEXT NOT NULL);
        """)
        db.execute("INSERT INTO budgets VALUES (?, ?, ?)", (TENANT, BUDGET_TOKENS, BUDGET_TOKENS))


def read_remaining(db):
    with closing(db.execute("SELECT remaining_tokens FROM budgets WHERE tenant_id = ?", (TENANT,))) as cursor:
        return cursor.fetchone()[0]


def snapshot(db):
    budget = dict(db.execute("SELECT tenant_id, budget_tokens, remaining_tokens FROM budgets WHERE tenant_id = ?", (TENANT,)).fetchone())
    rows = [dict(row) for row in db.execute("SELECT request_id, tenant_id, amount_tokens, worker_id FROM reservations ORDER BY request_id")]
    total = db.execute("SELECT COALESCE(SUM(amount_tokens), 0) FROM reservations WHERE tenant_id = ?", (TENANT,)).fetchone()[0]
    derived = budget["budget_tokens"] - total
    return {
        "reservation_rows": rows, "budget_row": budget,
        "derived_totals": {
            "reservation_count": len(rows), "reserved_tokens": total,
            "budget_minus_reservations": derived,
            "stored_remaining": budget["remaining_tokens"],
            "stored_minus_derived": budget["remaining_tokens"] - derived,
        },
    }


def conditional_reserve(db, worker_id, request_id):
    debit = db.execute("UPDATE budgets SET remaining_tokens = remaining_tokens - ? WHERE tenant_id = ? AND remaining_tokens >= ?",
                      (RESERVATION_TOKENS, TENANT, RESERVATION_TOKENS))
    inserted = 0
    if debit.rowcount == 1:
        inserted = db.execute("INSERT INTO reservations VALUES (?, ?, ?, ?)",
                              (request_id, TENANT, RESERVATION_TOKENS, worker_id)).rowcount
    return debit.rowcount, inserted


def concurrent_case(path, mode):
    barrier = threading.Barrier(2, timeout=BARRIER_SECONDS)
    results, errors = {}, []
    result_lock = threading.Lock()

    def worker(worker_id, request_id):
        try:
            with closing(connect(path)) as db:
                # This SELECT finishes before BEGIN, so both connections can read
                # the supplied opening balance without retaining a read lock.
                initial = read_remaining(db)
                barrier.wait()
                db.execute("BEGIN IMMEDIATE")
                try:
                    if mode == "unsafe":
                        # Deliberate defect: a write transaction does not repair a
                        # decision made from an earlier, stale balance.
                        debit_rows = inserted_rows = 0
                        if initial >= RESERVATION_TOKENS:
                            debit_rows = db.execute("UPDATE budgets SET remaining_tokens = ? WHERE tenant_id = ?",
                                                    (initial - RESERVATION_TOKENS, TENANT)).rowcount
                            inserted_rows = db.execute("INSERT INTO reservations VALUES (?, ?, ?, ?)",
                                                       (request_id, TENANT, RESERVATION_TOKENS, worker_id)).rowcount
                    else:
                        # Admission and the corresponding reservation row share
                        # one serialized transaction; never use initial here.
                        debit_rows, inserted_rows = conditional_reserve(db, worker_id, request_id)
                    db.execute("COMMIT")
                except Exception:
                    if db.in_transaction:
                        db.execute("ROLLBACK")
                    raise
                persisted = db.execute("SELECT COUNT(*) FROM reservations WHERE request_id = ? AND tenant_id = ?",
                                       (request_id, TENANT)).fetchone()[0]
                result = {"id": worker_id, "request_id": request_id, "initial_remaining_tokens": initial,
                          "requested_tokens": RESERVATION_TOKENS, "debit_rows": debit_rows,
                          "inserted_rows": inserted_rows, "persisted_reservations": persisted,
                          "decision": "admitted" if persisted else "refused"}
                with result_lock:
                    results[worker_id] = result
        except Exception as error:
            with result_lock:
                errors.append({"worker": worker_id, "error_class": type(error).__name__})
            barrier.abort()

    threads = [threading.Thread(target=worker, args=(f"worker-{letter}", f"REQUEST-{letter.upper()}"), daemon=True)
               for letter in ("a", "b")]
    for thread in threads:
        thread.start()
    deadline = time.monotonic() + WORKER_SECONDS
    for thread in threads:
        thread.join(max(0, deadline - time.monotonic()))
    if any(thread.is_alive() for thread in threads):
        barrier.abort()
        raise RuntimeError("bounded-worker-timeout")
    if errors:
        raise RuntimeError("worker-error")
    workers = [results[key] for key in sorted(results)]
    with closing(connect(path)) as db:
        return {"id": mode, "execution": "Two actual worker threads, two owned connections, one temporary shared SQLite file; initial reads synchronized before either write.",
                "workers": workers,
                "read_observations": [{"worker": row["id"], "remaining_tokens": row["initial_remaining_tokens"]} for row in workers],
                **snapshot(db), "steps": []}


class InjectedReservationFailure(RuntimeError):
    """Teaching interruption after a real debit but before reservation insertion."""


def rollback_case(path):
    steps = []
    with closing(connect(path)) as db:
        first_read = read_remaining(db)
        db.execute("BEGIN IMMEDIATE")
        try:
            debit = db.execute("UPDATE budgets SET remaining_tokens = remaining_tokens - ? WHERE tenant_id = ? AND remaining_tokens >= ?",
                               (RESERVATION_TOKENS, TENANT, RESERVATION_TOKENS))
            if debit.rowcount != 1:
                raise ValueError("The rollback teaching amount must fit the opening budget.")
            steps.append({"stage": "after-debit-before-insert", "debit_rows": debit.rowcount, **snapshot(db)})
            raise InjectedReservationFailure("supplied interruption")
        except InjectedReservationFailure as error:
            db.execute("ROLLBACK")
            steps.append({"stage": "after-rollback", "error_class": type(error).__name__,
                          "failure_point": "after-debit-before-insert", **snapshot(db)})
        except Exception:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
    # A new connection makes the persisted rollback state visible to a later attempt.
    with closing(connect(path)) as db:
        retry_read = read_remaining(db)
        db.execute("BEGIN IMMEDIATE")
        try:
            debit_rows, inserted_rows = conditional_reserve(db, "sequential-retry", "REQUEST-RETRY")
            db.execute("COMMIT")
        except Exception:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
        steps.append({"stage": "retry-committed", "debit_rows": debit_rows, "inserted_rows": inserted_rows, **snapshot(db)})
        return {"id": "rollback", "execution": "Sequential rollback and later retry on separate connections; this case is not a concurrency experiment.",
                "workers": [], "read_observations": [{"worker": "failure-attempt", "remaining_tokens": first_read},
                                                       {"worker": "retry-attempt", "remaining_tokens": retry_read}],
                **snapshot(db), "steps": steps}


def experiment(path, name):
    return rollback_case(path) if name == "rollback" else concurrent_case(path, name)


# The supervisor owns deletion. A timeout kills and waits for this worker process
# before TemporaryDirectory cleans its files, including any SQLite journal.
WORKER_CODE = """import json, runpy, sys
module = runpy.run_path(sys.argv[1])
try:
    print(json.dumps(module['experiment'](sys.argv[3], sys.argv[2]), allow_nan=False))
except Exception:
    sys.stderr.write('Worker experiment incomplete.\\n')
    raise SystemExit(2)
"""


def run_case(name):
    if name not in CASES:
        raise ValueError("Choose unsafe, atomic or rollback.")
    if type(RESERVATION_TOKENS) is not int or not 0 < RESERVATION_TOKENS <= BUDGET_TOKENS:
        raise ValueError("RESERVATION_TOKENS must be a positive integer no greater than the supplied budget.")
    with tempfile.TemporaryDirectory(prefix="lockedin-gateway-reservations-") as directory:
        path = Path(directory) / "reservations.sqlite3"
        initialize(path)
        try:
            child = subprocess.run([sys.executable, "-I", "-B", "-c", WORKER_CODE,
                                    str(Path(__file__).resolve()), name, str(path)],
                                   capture_output=True, text=True, timeout=PROCESS_SECONDS, env={})
        except subprocess.TimeoutExpired as error:
            raise RuntimeError("The local worker process exceeded its limit and was stopped before scratch cleanup.") from error
        if child.returncode != 0:
            raise RuntimeError("The local worker experiment did not finish; no completed observation was reported.")
        return json.loads(child.stdout)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--all", action="store_true", help="Run all three independent experiments (default)")
    group.add_argument("--case", choices=CASES, help="Run one named experiment")
    args = parser.parse_args()
    if sys.version_info < (3, 11):
        parser.exit(2, "Use Python 3.11 or newer.\n")
    try:
        print(json.dumps({"schema": "lockedin.gateway-concurrency/v1", "sqlite_version": sqlite3.sqlite_version,
                          "synthetic": True, "budget_tokens": BUDGET_TOKENS, "reservation_tokens": RESERVATION_TOKENS,
                          "scope": "Actual local SQLite work. Fixed synthetic tenant, not authentication, a distributed production guarantee, model inference or currency. Worker order is not a performance result.",
                          "cases": [run_case(name) for name in ((args.case,) if args.case else CASES)]}, indent=2, allow_nan=False))
    except (RuntimeError, ValueError, OSError, json.JSONDecodeError):
        parser.exit(1, "Local reservation experiment incomplete. Check Python, scratch-file permissions and SQLite availability; no production database was used.\n")


if __name__ == "__main__":
    main()
