"""Pass the DSN of a PostgreSQL test database where this user may create a table."""
import argparse
import time
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4

import psycopg
from psycopg import sql


def run_case(admin, a, b, table, case, guard, commit_first, expected_result, expected_final):
    admin.execute(sql.SQL("UPDATE {} SET price_cents=9900, version=7").format(table))
    read = sql.SQL("SELECT price_cents, version FROM {} WHERE id=42").format(table)
    assert a.execute(read).fetchone() == b.execute(read).fetchone() == (9900, 7)

    update = sql.SQL("UPDATE {} SET price_cents=%s, version=version+1 WHERE id=42").format(table)
    if guard:
        update += sql.SQL(" AND version=7")
    update += sql.SQL(" RETURNING price_cents, version")

    # Both editors finished reading before either writes. Keep A's row lock until B is waiting.
    with ThreadPoolExecutor(max_workers=1) as pool:
        a.execute("BEGIN ISOLATION LEVEL READ COMMITTED")
        try:
            assert a.execute(update, (8900,)).fetchone() == (8900, 8)
            pending = pool.submit(lambda: b.execute(update, (9500,)).fetchone())
            deadline = time.monotonic() + 8
            while True:
                blockers = admin.execute("SELECT pg_blocking_pids(%s)", (b.info.backend_pid,)).fetchone()[0]
                if a.info.backend_pid in blockers:
                    break
                if pending.done() or time.monotonic() >= deadline:
                    raise RuntimeError("Did not observe writer B waiting on A")
                time.sleep(0.02)
            a.execute("COMMIT" if commit_first else "ROLLBACK")
        finally:
            if a.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
                a.execute("ROLLBACK")
        result = pending.result(timeout=10)

    final = admin.execute(read).fetchone()
    assert result == expected_result and final == expected_final, (case, result, final)
    print(f"{case:20} B waited for A; B returned {result}; final {final}")


def main(dsn):
    table = sql.Identifier("conditional_price_" + uuid4().hex)
    with psycopg.connect(dsn, autocommit=True) as admin:
        print("PostgreSQL", admin.execute("SHOW server_version").fetchone()[0])
        admin.execute(sql.SQL("CREATE TABLE {} (id integer PRIMARY KEY, price_cents integer NOT NULL, "
                              "version bigint NOT NULL)").format(table))
        try:
            admin.execute(sql.SQL("INSERT INTO {} VALUES (42, 9900, 7)").format(table))
            with psycopg.connect(dsn, autocommit=True) as a, psycopg.connect(dsn, autocommit=True) as b:
                b.execute("SET default_transaction_isolation = 'read committed'")
                b.execute("SET statement_timeout = '15s'")
                run_case(admin, a, b, table, "plain / commit", False, True, (9500, 9), (9500, 9))
                run_case(admin, a, b, table, "guard / commit", True, True, None, (8900, 8))
                run_case(admin, a, b, table, "guard / rollback", True, False, (9500, 8), (9500, 8))
        finally:
            admin.execute(sql.SQL("DROP TABLE {}").format(table))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("dsn")
    main(parser.parse_args().dsn)
