"""Run with Python 3 to repeat RedCoat's synthetic payroll backup demonstration."""
import hashlib
import json
import sqlite3
import tempfile
from contextlib import closing
from pathlib import Path

PAYROLL = [(1, 135000), (2, 148500), (3, 161250), (4, 125000), (5, 140750), (6, 153500)]


def summary(db):
    rows = db.execute("SELECT item, cents FROM payroll ORDER BY item").fetchall()
    canonical = json.dumps(rows, separators=(",", ":")).encode("utf-8")
    return {
        "records": len(rows),
        "total_cents": sum(row[1] for row in rows),
        "data_sha256": hashlib.sha256(canonical).hexdigest(),
    }


def run(folder):
    snapshot = folder / "backup.sqlite"
    with closing(sqlite3.connect(folder / "working.sqlite")) as live:
        live.execute("CREATE TABLE payroll (item INTEGER PRIMARY KEY, cents INTEGER NOT NULL)")
        live.executemany("INSERT INTO payroll VALUES (?, ?)", PAYROLL)
        live.commit()
        expected = summary(live)
        with closing(sqlite3.connect(snapshot)) as backup:
            live.backup(backup)
        live.execute("INSERT INTO payroll VALUES (7, 15000)")
        live.commit()
    with closing(sqlite3.connect(snapshot.as_uri() + "?mode=ro", uri=True)) as backup:
        with closing(sqlite3.connect(folder / "restored.sqlite")) as restored:
            backup.backup(restored)
            recovered = summary(restored)
            integrity = restored.execute("PRAGMA integrity_check").fetchone()[0]
    if expected != recovered or integrity != "ok":
        raise RuntimeError("The restored records did not pass verification.")
    return {
        "scope": "SQLite restore drill with synthetic payroll records",
        "backup": expected,
        "restored": recovered,
        "database_integrity": integrity,
        "post_backup_item_excluded": True,
    }


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as scratch:
        print(json.dumps(run(Path(scratch)), indent=2))
