#!/usr/bin/env python3
"""Local teaching lab: atomic export admission, NOT a production API/worker.

Run: python3 retry-lab.py
Uses Python's standard library, temporary SQLite files, subprocess termination,
and concurrent threads. No network calls, credentials, or persistent user files.
SQLite serializes writers; this does not test PostgreSQL isolation or failover.
"""
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
import uuid

PAYLOAD = {"dataset_version": "snapshot-7", "format": "csv"}


class PayloadMismatch(Exception):
    pass


class QuotaExhausted(Exception):
    pass


def connect(path):
    return sqlite3.connect(path, timeout=10, isolation_level=None)


def initialise(path, remaining=10):
    with connect(path) as db:
        db.executescript("""
        CREATE TABLE quota(tenant TEXT PRIMARY KEY, remaining INTEGER NOT NULL CHECK(remaining >= 0));
        CREATE TABLE requests(
          tenant TEXT NOT NULL, operation TEXT NOT NULL, request_key TEXT NOT NULL,
          payload_hash TEXT NOT NULL, receipt TEXT NOT NULL,
          PRIMARY KEY(tenant, operation, request_key));
        CREATE TABLE jobs(id TEXT PRIMARY KEY, tenant TEXT NOT NULL, payload TEXT NOT NULL);
        CREATE TABLE outbox(id TEXT PRIMARY KEY, job_id TEXT NOT NULL UNIQUE);
        """)
        db.executemany("INSERT INTO quota VALUES (?, ?)", [("alpha", remaining), ("beta", remaining)])


def admit(path, tenant, key, payload, failpoint=None):
    # tenant represents already-authenticated, authorized context in this lab.
    # Canonicalization is defined only for these validated string fields.
    if set(payload) != {"dataset_version", "format"} or payload["format"] != "csv":
        raise ValueError("unsupported payload")
    if not isinstance(payload["dataset_version"], str) or not payload["dataset_version"]:
        raise ValueError("dataset_version must be a nonempty string")
    if not isinstance(key, str) or not key:
        raise ValueError("request key must be a nonempty string")
    body = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    fingerprint = hashlib.sha256(body.encode()).hexdigest()
    db = connect(path)

    def crash(point):
        if failpoint == point:
            os._exit(73)  # Deliberate child-process crash; no graceful rollback.

    try:
        db.execute("BEGIN IMMEDIATE")
        previous = db.execute(
            "SELECT payload_hash, receipt FROM requests WHERE tenant=? AND operation=? AND request_key=?",
            (tenant, "create_export", key),
        ).fetchone()
        if previous:
            if previous[0] != fingerprint:
                raise PayloadMismatch("same request key, different normalized payload")
            db.execute("COMMIT")
            return json.loads(previous[1])
        job_id = str(uuid.uuid4())
        receipt = {"status": 202, "job_id": job_id, "status_url": f"/exports/{job_id}"}
        db.execute("INSERT INTO requests VALUES (?, ?, ?, ?, ?)",
                   (tenant, "create_export", key, fingerprint, json.dumps(receipt)))
        crash("after_request")
        changed = db.execute(
            "UPDATE quota SET remaining=remaining-1 WHERE tenant=? AND remaining>0", (tenant,)
        ).rowcount
        if changed != 1:
            raise QuotaExhausted("no export credits available")
        crash("after_quota")
        db.execute("INSERT INTO jobs VALUES (?, ?, ?)", (job_id, tenant, body))
        crash("after_job")
        db.execute("INSERT INTO outbox VALUES (?, ?)", (str(uuid.uuid4()), job_id))
        crash("before_commit")
        db.execute("COMMIT")
        crash("after_commit")
        return receipt
    except Exception:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise
    finally:
        db.close()


def state(path, tenant="alpha"):
    db = connect(path)
    try:
        return (
            db.execute("SELECT count(*) FROM requests WHERE tenant=?", (tenant,)).fetchone()[0],
            db.execute("SELECT count(*) FROM jobs WHERE tenant=?", (tenant,)).fetchone()[0],
            db.execute("SELECT count(*) FROM outbox o JOIN jobs j ON o.job_id=j.id WHERE j.tenant=?", (tenant,)).fetchone()[0],
            db.execute("SELECT remaining FROM quota WHERE tenant=?", (tenant,)).fetchone()[0],
        )
    finally:
        db.close()


def check(condition, message):
    if not condition:
        raise AssertionError(message)


def expect(exception, action):
    try:
        action()
    except exception:
        return
    raise AssertionError(f"expected {exception.__name__}")


def run_tests():
    with tempfile.TemporaryDirectory(prefix="export-retry-lab-") as folder:
        for point in ("after_request", "after_quota", "after_job", "before_commit", "after_commit"):
            path = str(Path(folder) / f"{point}.sqlite")
            initialise(path)
            result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--crash-child", path, point], check=False)
            check(result.returncode == 73, f"child did not reach {point}")
            expected = (1, 1, 1, 9) if point == "after_commit" else (0, 0, 0, 10)
            check(state(path) == expected, f"unexpected crash state: {point}: {state(path)}")
            if point == "after_commit":
                db = connect(path)
                original = json.loads(db.execute("SELECT receipt FROM requests").fetchone()[0])
                db.close()
            receipt = admit(path, "alpha", "request-1", PAYLOAD)
            if point == "after_commit":
                check(receipt == original, "lost-response retry changed original receipt")
            check(admit(path, "alpha", "request-1", PAYLOAD) == receipt, "receipt was not replayed")
            check(state(path) == (1, 1, 1, 9), "retry duplicated a durable effect")
            print(f"PASS crash/{point}: state {expected}; retry -> (1 request, 1 job, 1 outbox, 9 credits)")

        path = str(Path(folder) / "concurrent.sqlite")
        initialise(path)
        barrier = Barrier(8)
        def submit(_):
            barrier.wait(timeout=10)
            return admit(path, "alpha", "shared-request", PAYLOAD)
        with ThreadPoolExecutor(max_workers=8) as pool:
            receipts = list(pool.map(submit, range(8)))
        check(all(item == receipts[0] for item in receipts), "concurrent receipts differ")
        check(state(path) == (1, 1, 1, 9), "concurrent requests duplicated an effect")
        print("PASS concurrency: 8 callers, 1 stable receipt, 1 quota debit")
        expect(PayloadMismatch, lambda: admit(path, "alpha", "shared-request", {**PAYLOAD, "dataset_version": "snapshot-8"}))
        check(state(path) == (1, 1, 1, 9), "mismatch changed durable state")
        print("PASS payload mismatch: rejected, durable state unchanged")
        other = admit(path, "beta", "shared-request", PAYLOAD)
        check(other != receipts[0] and state(path, "beta") == (1, 1, 1, 9), "tenant scopes collided")
        print("PASS tenant namespace: same key, separate receipt and quota")
        new_intent = admit(path, "alpha", "another-request", PAYLOAD)
        check(new_intent != receipts[0] and state(path) == (2, 2, 2, 8), "new intent was incorrectly deduplicated")
        print("PASS new intent: same payload + new key creates another export")
        empty = str(Path(folder) / "empty.sqlite")
        initialise(empty, remaining=0)
        expect(QuotaExhausted, lambda: admit(empty, "alpha", "request-1", PAYLOAD))
        check(state(empty) == (0, 0, 0, 0), "quota rejection left partial state")
        print("PASS exhausted quota: full rollback, no accepted request")
        print("10 cases passed. Scope: admission transaction only; no worker, broker, or provider test.")


if __name__ == "__main__":
    if len(sys.argv) == 4 and sys.argv[1] == "--crash-child":
        admit(sys.argv[2], "alpha", "request-1", PAYLOAD, failpoint=sys.argv[3])
        raise SystemExit("unreached failpoint")
    elif len(sys.argv) == 1:
        run_tests()
    else:
        raise SystemExit("Usage: python3 retry-lab.py")
