"""Synthetic rollback example. Python 3 standard library; in-memory data only.

This models an application data contract, not an AWS deployment or a real incident.
It makes no network requests and writes no files.
"""
import sqlite3


def old_reader(db):
    statuses = [row[0] for row in db.execute("SELECT status FROM orders")]
    unsupported = set(statuses) - {"new", "paid"}
    if unsupported:
        raise ValueError("unsupported status: " + ", ".join(sorted(unsupported)))
    return statuses


def main():
    db = sqlite3.connect(":memory:")
    try:
        db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT NOT NULL)")
        db.execute("INSERT INTO orders VALUES (1, 'paid')")
        assert old_reader(db) == ["paid"]
        print("Before cutover: old reader accepts 'paid'")

        # The new application writes a value the old reader cannot interpret.
        # The SQL column definition has not changed.
        db.execute("UPDATE orders SET status = 'refunded' WHERE id = 1")
        print("New writer: status changed to 'refunded'")

        # Model routing a request back to the old application against current data.
        try:
            old_reader(db)
        except ValueError as error:
            print("After traffic reversal: " + str(error))
        else:
            raise AssertionError("The old reader should reject the new value")
        assert db.execute("SELECT status FROM orders WHERE id = 1").fetchone()[0] == "refunded"
        print("Simple rollback gate: BLOCKED (data contract is incompatible)")
    finally:
        db.close()


if __name__ == "__main__":
    main()
