"""Test SQLite permissions against fictional records, without an agent or network."""
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory


def denied(connection, statement):
    try:
        connection.execute(statement)
    except sqlite3.DatabaseError as error:
        return str(error)
    raise AssertionError("Operation unexpectedly succeeded")


with TemporaryDirectory() as directory:
    state = Path(directory) / "sample.db"
    with sqlite3.connect(state) as store:
        store.executescript("""
            CREATE TABLE review_metadata(request_id, operation);
            INSERT INTO review_metadata VALUES (7, 'review booking');
            CREATE TABLE bookings(request_id, booking_label);
            INSERT INTO bookings VALUES (7, 'sample booking');
        """)
        baseline = store.execute("SELECT * FROM bookings").fetchall()

        with sqlite3.connect(f"{state.as_uri()}?mode=ro", uri=True) as auditor:
            assert auditor.execute("SELECT * FROM review_metadata").fetchone() == (
                7, "review booking"
            )
            write_error = denied(auditor, "UPDATE bookings SET booking_label = 'changed'")
            assert "readonly" in write_error
            assert auditor.execute("SELECT * FROM bookings").fetchall() == baseline
            print("read-only: review metadata allowed, booking write denied, booking read allowed")

            def review_tables_only(action, table, *_):
                if action == sqlite3.SQLITE_READ and table != "review_metadata":
                    return sqlite3.SQLITE_DENY
                return sqlite3.SQLITE_OK

            auditor.set_authorizer(review_tables_only)
            assert auditor.execute("SELECT * FROM review_metadata").fetchone() == (
                7, "review booking"
            )
            read_error = denied(auditor, "SELECT * FROM bookings")
            assert "prohibited" in read_error
            write_error = denied(auditor, "UPDATE bookings SET booking_label = 'changed'")
            assert "readonly" in write_error
            print("read-only plus table restriction: review metadata allowed, booking write and read denied")

        assert store.execute("SELECT * FROM bookings").fetchall() == baseline
        print("protected booking rows unchanged")
