"""Run with python3 replay.py. Requires Python 3.8+ and no external packages.

This single-client fixture uses immutable source records and two local SQLite
files for the ticket system and workflow receipts. Amounts are USD cents.
The ticket system enforces a unique invoice key. A live pilot must verify its
destination supports an equivalent guarantee before retrying a write.
"""
from contextlib import closing
from pathlib import Path
import sqlite3
import subprocess
import sys
from tempfile import TemporaryDirectory


PURCHASE_ORDERS = {"PO-101": 12000, "PO-102": 15000, "PO-103": 7500}
INVOICES = [
    ("INV-101", "PO-101", 12000),
    ("INV-102", "PO-102", 18000),
    ("INV-103", "PO-103", 7500),
]
BUYER = "Casey (buyer)"
INTERRUPTED = 75


def missing_receipts(workflow):
    """Reconcile from the source register, independently of the delivery queue."""
    received = {row[0] for row in workflow.execute("SELECT invoice FROM receipts")}
    return [invoice for invoice in INVOICES if invoice[0] not in received]


def run_worker(root, interrupt):
    with closing(sqlite3.connect(root / "tickets.db")) as desk, closing(
        sqlite3.connect(root / "workflow.db")
    ) as workflow:
        for invoice, po, amount in missing_receipts(workflow):
            difference = amount - PURCHASE_ORDERS[po]
            ticket_id = None
            outcome = "amount matched"
            if difference:
                with desk:
                    created = desk.execute(
                        "INSERT INTO tickets(invoice, difference, owner, status) "
                        "VALUES (?, ?, ?, 'open') ON CONFLICT(invoice) DO NOTHING",
                        (invoice, difference, BUYER),
                    ).rowcount
                    ticket_id = desk.execute(
                        "SELECT id FROM tickets WHERE invoice = ?", (invoice,)
                    ).fetchone()[0]
                verb = "created" if created else "reused"
                print(f"{invoice} {verb} ticket T-{ticket_id} for difference USD {difference / 100:.2f}")
                if interrupt:
                    print(f"Worker stopped after the ticket commit and before the {invoice} receipt.")
                    return INTERRUPTED
                outcome = "buyer review"
            with workflow:
                workflow.execute(
                    "INSERT INTO receipts(invoice, outcome, ticket_id) VALUES (?, ?, ?)",
                    (invoice, outcome, ticket_id),
                )
            print(f"{invoice} receipt saved ({outcome})")
    return 0


def worker_process(root, phase, expected_code):
    result = subprocess.run([sys.executable, __file__, phase, str(root)], check=False)
    if result.returncode != expected_code:
        raise RuntimeError(f"{phase} returned {result.returncode}, expected {expected_code}")


def replay(root):
    with closing(sqlite3.connect(root / "tickets.db")) as desk:
        desk.execute(
            "CREATE TABLE tickets(id INTEGER PRIMARY KEY, invoice TEXT NOT NULL UNIQUE, "
            "difference INTEGER NOT NULL, owner TEXT NOT NULL, status TEXT NOT NULL)"
        )
    with closing(sqlite3.connect(root / "workflow.db")) as workflow:
        workflow.execute(
            "CREATE TABLE receipts(invoice TEXT PRIMARY KEY, outcome TEXT NOT NULL, ticket_id INTEGER)"
        )
    print("Synthetic local pilot | 3 source invoices | 3 purchase orders", flush=True)
    worker_process(root, "interrupt", INTERRUPTED)

    with closing(sqlite3.connect(root / "workflow.db")) as workflow:
        gaps = [row[0] for row in missing_receipts(workflow)]
        receipts = workflow.execute("SELECT invoice FROM receipts ORDER BY invoice").fetchall()
        assert receipts == [("INV-101",)] and gaps == ["INV-102", "INV-103"]
        print(f"Last receipt before restart: {receipts[-1][0]}")
        print(f"Missing receipts in source-register check: {', '.join(gaps)}", flush=True)

    worker_process(root, "recover", 0)
    worker_process(root, "recover", 0)
    with closing(sqlite3.connect(root / "workflow.db")) as workflow, closing(
        sqlite3.connect(root / "tickets.db")
    ) as desk:
        receipts = workflow.execute(
            "SELECT invoice, outcome, ticket_id FROM receipts ORDER BY invoice"
        ).fetchall()
        tickets = desk.execute("SELECT id, invoice, difference, owner, status FROM tickets").fetchall()
        assert receipts == [
            ("INV-101", "amount matched", None),
            ("INV-102", "buyer review", 1),
            ("INV-103", "amount matched", None),
        ]
        assert tickets == [(1, "INV-102", 3000, BUYER, "open")]
        print(f"After recovery and a second pass: {len(receipts)} receipts, {len(tickets)} ticket.")
        ticket_id, invoice, _, owner, status = tickets[0]
        print(f"T-{ticket_id} | {invoice} | {status} | {owner}")
        print("Pilot stops at review. Payment approval and bank access are outside this fixture.")


if __name__ == "__main__":
    if len(sys.argv) == 1:
        with TemporaryDirectory() as temp:
            replay(Path(temp))
    elif len(sys.argv) == 3 and sys.argv[1] in ("interrupt", "recover"):
        sys.exit(run_worker(Path(sys.argv[2]), interrupt=sys.argv[1] == "interrupt"))
    else:
        sys.exit("Usage: python3 replay.py")
