"""Run from the directory containing fk_demo.py. All databases are in memory."""
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
from fk_demo import open_db

script = Path(__file__).with_name("fk_demo.py")
for mode, status, rows, accepted in [("off", 0, 2, True), ("on", 1, 0, False)]:
    proc = subprocess.run(
        [sys.executable, str(script), "--enforce", mode],
        capture_output=True, text=True, check=False,
    )
    report = json.loads(proc.stdout)
    assert proc.returncode == status, proc
    assert report["accepted"] is accepted
    assert report["foreign_keys"] == (mode == "on")
    assert report["result_rows"] == rows
    assert report["violations"] == ([["results", 2, "jobs", 0]] if mode == "off" else [])
    assert proc.stderr == ("ERROR: FOREIGN KEY constraint failed\n" if mode == "on" else "")
print("PASS: same batch accepted with OFF; rejected and fully rolled back with ON")

con = open_db(False)
try:
    con.execute("INSERT INTO results VALUES (7, 999)")
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    assert con.execute("PRAGMA foreign_key_check").fetchall() == [("results", 7, "jobs", 0)]
finally:
    con.close()
print("PASS: enabling checks does not repair an existing orphan")

con = open_db(False)
try:
    con.execute("BEGIN")
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (0,)
    con.execute("ROLLBACK")
    con.execute("PRAGMA foreign_keys = ON")
    assert con.execute("PRAGMA foreign_keys").fetchone() == (1,)
    con.execute("INSERT INTO results VALUES (1, 1)")
    try:
        con.execute("DELETE FROM jobs WHERE id = 1")
    except sqlite3.IntegrityError:
        pass
    else:
        raise AssertionError("parent deletion was not rejected")
    assert con.execute("SELECT COUNT(*) FROM jobs").fetchone() == (1,)
finally:
    con.close()
print("PASS: transaction-time toggle ignored; referenced parent deletion rejected")

for args, status in [(["--help"], 0), (["--enforce", "maybe"], 2)]:
    proc = subprocess.run([sys.executable, str(script), *args], capture_output=True, text=True)
    assert proc.returncode == status, proc
print("PASS: help and invalid argument exit codes")
