#!/usr/bin/env python3
"""Apply DB_CHANGES_STATUS_ED_2 in one transaction. Usage: apply_status_ed_3.py dry|live"""
import json, sqlite3, sys
DB = "../../../resources/tools/substrate/index.html"
SRC = "../../../resources/tools/provenance/index.html#s-c8323c9c2b4bde51"
NOTE = "status-ed-3 apply 2026-09-30, backup pre-status-ed-3-2026-09-30"
mode = sys.argv[1]; assert mode in ("dry", "live")
lines = [json.loads(l) for l in open(SRC) if l.strip()]
assert len(lines) == 6
con = sqlite3.connect(DB, timeout=60, isolation_level=None)
con.execute("PRAGMA busy_timeout=60000")
assert con.execute("PRAGMA database_list").fetchone()[2].endswith("research register")
pre = con.execute("select coalesce(max(id),0) from edit_history").fetchone()[0]
con.execute("BEGIN IMMEDIATE")
try:
    for d in lines:
        assert d["table"] == "findings" and d["column"] in ("status", "notes")
        cur = con.execute("select %s from findings where id=?" % d["column"], (d["row_id"],)).fetchone()
        if cur is None: raise RuntimeError("row missing %s" % d["id"])
        cur = cur[0]
        if d["action"] == "set":
            if cur != d["old_value"]: raise RuntimeError("old_value mismatch %s live=%r" % (d["id"], cur))
            con.execute("update findings set status=? where id=?", (d["new_value"], d["row_id"]))
        elif d["action"] == "append_note":
            add = d["new_value"]
            if cur and add in cur: raise RuntimeError("note already present %s" % d["id"])
            con.execute("update findings set notes=? where id=?", (((cur + "\n") if cur else "") + add, d["row_id"]))
        else: raise RuntimeError("action " + d["action"])
    post = con.execute("select coalesce(max(id),0) from edit_history").fetchone()[0]
    ids = [r[0] for r in con.execute("select id from edit_history where id>? order by id", (pre,))]
    n = con.execute("update edit_history set notes=coalesce(notes||' | ','')||? where id>?", (NOTE, pre)).rowcount
    st = dict(con.execute("select status,count(*) from findings group by 1").fetchall())
    nf = con.execute("select count(*) from findings").fetchone()[0]
    ic = con.execute("pragma integrity_check").fetchone()[0]
    want = {"Candidate":138,"Confirmed":77,"Falsified":68,"Observed":221,"Parked":37,"Supported":141}
    good = st == want and nf == 682 and ic == "ok"
    print("verify in-txn:", "PASS" if good else "FAIL", st, nf, ic)
    if mode == "live" and good: con.execute("COMMIT"); print("COMMITTED")
    else: con.execute("ROLLBACK"); print("ROLLED BACK")
except Exception:
    con.execute("ROLLBACK"); print("ABORTED, no write"); raise
print("edit_history ids", ids, "pre_max", pre, "post_max", post, "noted", n)
