"""Disposable SQLite WAL backup example; accepts no live database path."""
from contextlib import closing
from pathlib import Path
import sqlite3
import tempfile


def main():
    with tempfile.TemporaryDirectory(prefix="ithy-sqlite-toy-") as temporary:
        directory = Path(temporary)
        source_path = directory / "toy.db"
        backup_path = directory / "toy-backup.db"
        expected = [(1, "alpha"), (2, "beta"), (3, "gamma")]
        with closing(sqlite3.connect(source_path)) as source:
            source.execute("PRAGMA wal_autocheckpoint=0")
            mode = source.execute("PRAGMA journal_mode=WAL").fetchone()[0]
            if mode.lower() != "wal":
                raise RuntimeError("WAL mode was not available")
            source.execute("CREATE TABLE sample (id INTEGER PRIMARY KEY, value TEXT NOT NULL)")
            source.executemany("INSERT INTO sample VALUES (?, ?)", expected)
            source.commit()
            wal_present = source_path.with_name("toy.db-wal").exists()
            with closing(sqlite3.connect(backup_path)) as destination:
                source.backup(destination)
            with closing(sqlite3.connect(backup_path)) as restored:
                actual = restored.execute("SELECT id, value FROM sample ORDER BY id").fetchall()
                integrity = restored.execute("PRAGMA integrity_check").fetchall()
                if actual != expected or integrity != [("ok",)]:
                    raise RuntimeError("Toy backup verification failed")
            result = dict(sqlite_version=sqlite3.sqlite_version, journal_mode=mode,
                          wal_present_during_backup=wal_present, rows=actual,
                          integrity_check=integrity[0][0])
    return result


if __name__ == "__main__":
    import json
    print(json.dumps(main(), sort_keys=True))
