#!/usr/bin/env python3
"""Bank batch-338: Rule 296 visible water-fauna singular/third past perception."""

from __future__ import annotations

import datetime as dt
import json
import re
import sqlite3

from process_ledger import ensure_schema, record_event

DB = "/mnt/donto-data/donto-resources/research/translation-training/kuku-yalanji-runpod-2026-06-30/synthetic/claude-synthetic-v1-2026-07-02/synthetic.db"
LABEL = "batch-338"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-338-visible-water-fauna-singular-third-past-perception-after-rule295-process.md"

TARGET_EVIDENCE = {
    "ngawiya": "Core lexicon line 744 gives ngawiya as 'sea turtle', neutral, with a hunted-food note. Rule 296 selects visible sea-turtle reference only and leaves hunting, turtle-spearing, cooking, and eating rows closed.",
    "ngujay": "Core lexicon line 745 gives ngujay as 'freshwater turtle', neutral. Rule 296 selects visible freshwater-turtle reference only.",
    "kuyu": "Core lexicon line 751 gives kuyu as 'fish', neutral as food/object. Rule 296 selects visible generic-fish reference only and leaves catching, spearing, bait, cooking, and eating rows closed.",
    "yawu": "Core lexicon line 753 gives yawu as 'stingray', ambiguous. Rule 296 selects visible stingray reference only and leaves danger, hunting, spearing, and catch rows closed.",
    "judi": "Core lexicon line 754 gives judi as 'barramundi' and identifies it as the Yalanji form. Rule 296 selects visible barramundi reference only.",
    "ngalkun": "Core lexicon line 755 gives ngalkun as 'mullet', neutral. Rule 296 selects visible mullet reference only.",
    "kubarr": "Core lexicon line 756 gives kubarr as 'big black freshwater eel', neutral. Rule 296 selects visible freshwater-eel reference only and does not open colour/property rows.",
    "kiju": "Core lexicon line 757 gives kiju as 'mudcrab', neutral. Rule 296 selects visible mudcrab reference only and leaves biting, catching, and cooking rows closed.",
    "wakal": "Core lexicon line 758 gives wakal as 'prawn, lobster', neutral. Rule 296 selects visible prawn reference only and leaves catching, cooking, and eating rows closed.",
    "julul": "Core lexicon line 759 gives julul as 'oyster', neutral. Rule 296 selects visible oyster reference only and leaves gathering, eating, and shore/ecology rows closed.",
}

SUPPORT_EVIDENCE = (
    "Patz pronoun tables source bare nominative ngayu, yundu, nyulu, bula, and jana; local-demonstrative lines "
    "source yaluy 'here' and yinyay 'there'; Patz examples source nyaji-ny 'see-PAST', and the tense section "
    "sources past -ny. Rule 296 uses corpus-conventional nyajin as the past visual-perception surface."
)

TARGET_ORDER = ["ngawiya", "ngujay", "kuyu", "yawu", "judi", "ngalkun", "kubarr", "kiju", "wakal", "julul"]
FRAME_SPECS = [
    ("ngayu", "yaluy"),
    ("yundu", "yinyay"),
    ("nyulu", "yaluy"),
    ("bula", "yinyay"),
    ("jana", "yaluy"),
]

DENY_KUKU = {
    "yuday", "kulil", "nuwi", "yaburr", "badibu",
    "ngawiyangka", "ngujayngka", "kuyubu", "yawubu", "judibu", "ngalkundu", "kubarrbu",
    "kijubu", "wakalbu", "jululbu", "ngawiyaka", "ngujayka", "kuyuka", "yawuka", "judika",
    "ngalkunka", "kubarrka", "kijuka", "wakalka", "jululka", "ngawiyanga", "ngujaynga",
    "kuyunga", "yawunga", "judinga", "ngalkunga", "kubarrnga", "kijunga", "wakalnga", "jululnga",
    "nganya", "yununy", "nyunguny", "bulangan", "janangan", "ngaykunku", "yununku",
    "nyungunku", "bulanka", "jananka", "ngaykundu", "yunundu", "nyungundu", "bulanda",
    "jananda", "yalungku", "yaluyngku", "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajil", "nyaji-l", "nyaji-nka", "nyaji-l-nyaji", "milka",
}
DENY_ENGLISH = (
    "catch", "caught", "catching", "spear", "spearing", "hunt", "hunting", "kill", "bite", "biting",
    "cook", "cooking", "roast", "eat", "eating", "food", "meat", "bait", "net", "hook", "danger",
    "dangerous", "story", "place", "reef", "shore", "swim", "bleeding", "black", "colour", "color",
    "gather", "gathering", "lobster",
)


def row(seq: int, english: str, kuku: str, analysis: str, frame: str, words: list[str]) -> tuple:
    target = words[1]
    evidence = f"{TARGET_EVIDENCE[target]} {SUPPORT_EVIDENCE}"
    return (seq, english, kuku, analysis, frame, 3, json.dumps(words, ensure_ascii=False), json.dumps([], ensure_ascii=False), evidence, "0.86")


ROWS = [
    row(1, "I saw the sea turtle here.", "Ngayu ngawiya yaluy nyajin.", "ngayu ngawiya yaluy nyajin | 1sg.NOM sea.turtle here see.PAST", "r296_1sg_here_water_fauna_see_ngawiya", ["ngayu", "ngawiya", "yaluy", "nyajin"]),
    row(2, "I saw the freshwater turtle here.", "Ngayu ngujay yaluy nyajin.", "ngayu ngujay yaluy nyajin | 1sg.NOM freshwater.turtle here see.PAST", "r296_1sg_here_water_fauna_see_ngujay", ["ngayu", "ngujay", "yaluy", "nyajin"]),
    row(3, "I saw the fish here.", "Ngayu kuyu yaluy nyajin.", "ngayu kuyu yaluy nyajin | 1sg.NOM fish here see.PAST", "r296_1sg_here_water_fauna_see_kuyu", ["ngayu", "kuyu", "yaluy", "nyajin"]),
    row(4, "I saw the stingray here.", "Ngayu yawu yaluy nyajin.", "ngayu yawu yaluy nyajin | 1sg.NOM stingray here see.PAST", "r296_1sg_here_water_fauna_see_yawu", ["ngayu", "yawu", "yaluy", "nyajin"]),
    row(5, "I saw the barramundi here.", "Ngayu judi yaluy nyajin.", "ngayu judi yaluy nyajin | 1sg.NOM barramundi here see.PAST", "r296_1sg_here_water_fauna_see_judi", ["ngayu", "judi", "yaluy", "nyajin"]),
    row(6, "I saw the mullet here.", "Ngayu ngalkun yaluy nyajin.", "ngayu ngalkun yaluy nyajin | 1sg.NOM mullet here see.PAST", "r296_1sg_here_water_fauna_see_ngalkun", ["ngayu", "ngalkun", "yaluy", "nyajin"]),
    row(7, "I saw the freshwater eel here.", "Ngayu kubarr yaluy nyajin.", "ngayu kubarr yaluy nyajin | 1sg.NOM freshwater.eel here see.PAST", "r296_1sg_here_water_fauna_see_kubarr", ["ngayu", "kubarr", "yaluy", "nyajin"]),
    row(8, "I saw the mudcrab here.", "Ngayu kiju yaluy nyajin.", "ngayu kiju yaluy nyajin | 1sg.NOM mudcrab here see.PAST", "r296_1sg_here_water_fauna_see_kiju", ["ngayu", "kiju", "yaluy", "nyajin"]),
    row(9, "I saw the prawn here.", "Ngayu wakal yaluy nyajin.", "ngayu wakal yaluy nyajin | 1sg.NOM prawn here see.PAST", "r296_1sg_here_water_fauna_see_wakal", ["ngayu", "wakal", "yaluy", "nyajin"]),
    row(10, "I saw the oyster here.", "Ngayu julul yaluy nyajin.", "ngayu julul yaluy nyajin | 1sg.NOM oyster here see.PAST", "r296_1sg_here_water_fauna_see_julul", ["ngayu", "julul", "yaluy", "nyajin"]),
    row(11, "You saw the sea turtle there.", "Yundu ngawiya yinyay nyajin.", "yundu ngawiya yinyay nyajin | 2sg.NOM sea.turtle there see.PAST", "r296_2sg_there_water_fauna_see_ngawiya", ["yundu", "ngawiya", "yinyay", "nyajin"]),
    row(12, "You saw the freshwater turtle there.", "Yundu ngujay yinyay nyajin.", "yundu ngujay yinyay nyajin | 2sg.NOM freshwater.turtle there see.PAST", "r296_2sg_there_water_fauna_see_ngujay", ["yundu", "ngujay", "yinyay", "nyajin"]),
    row(13, "You saw the fish there.", "Yundu kuyu yinyay nyajin.", "yundu kuyu yinyay nyajin | 2sg.NOM fish there see.PAST", "r296_2sg_there_water_fauna_see_kuyu", ["yundu", "kuyu", "yinyay", "nyajin"]),
    row(14, "You saw the stingray there.", "Yundu yawu yinyay nyajin.", "yundu yawu yinyay nyajin | 2sg.NOM stingray there see.PAST", "r296_2sg_there_water_fauna_see_yawu", ["yundu", "yawu", "yinyay", "nyajin"]),
    row(15, "You saw the barramundi there.", "Yundu judi yinyay nyajin.", "yundu judi yinyay nyajin | 2sg.NOM barramundi there see.PAST", "r296_2sg_there_water_fauna_see_judi", ["yundu", "judi", "yinyay", "nyajin"]),
    row(16, "You saw the mullet there.", "Yundu ngalkun yinyay nyajin.", "yundu ngalkun yinyay nyajin | 2sg.NOM mullet there see.PAST", "r296_2sg_there_water_fauna_see_ngalkun", ["yundu", "ngalkun", "yinyay", "nyajin"]),
    row(17, "You saw the freshwater eel there.", "Yundu kubarr yinyay nyajin.", "yundu kubarr yinyay nyajin | 2sg.NOM freshwater.eel there see.PAST", "r296_2sg_there_water_fauna_see_kubarr", ["yundu", "kubarr", "yinyay", "nyajin"]),
    row(18, "You saw the mudcrab there.", "Yundu kiju yinyay nyajin.", "yundu kiju yinyay nyajin | 2sg.NOM mudcrab there see.PAST", "r296_2sg_there_water_fauna_see_kiju", ["yundu", "kiju", "yinyay", "nyajin"]),
    row(19, "You saw the prawn there.", "Yundu wakal yinyay nyajin.", "yundu wakal yinyay nyajin | 2sg.NOM prawn there see.PAST", "r296_2sg_there_water_fauna_see_wakal", ["yundu", "wakal", "yinyay", "nyajin"]),
    row(20, "You saw the oyster there.", "Yundu julul yinyay nyajin.", "yundu julul yinyay nyajin | 2sg.NOM oyster there see.PAST", "r296_2sg_there_water_fauna_see_julul", ["yundu", "julul", "yinyay", "nyajin"]),
    row(21, "He saw the sea turtle here.", "Nyulu ngawiya yaluy nyajin.", "nyulu ngawiya yaluy nyajin | 3sg.NOM sea.turtle here see.PAST", "r296_3sg_here_water_fauna_see_ngawiya", ["nyulu", "ngawiya", "yaluy", "nyajin"]),
    row(22, "He saw the freshwater turtle here.", "Nyulu ngujay yaluy nyajin.", "nyulu ngujay yaluy nyajin | 3sg.NOM freshwater.turtle here see.PAST", "r296_3sg_here_water_fauna_see_ngujay", ["nyulu", "ngujay", "yaluy", "nyajin"]),
    row(23, "He saw the fish here.", "Nyulu kuyu yaluy nyajin.", "nyulu kuyu yaluy nyajin | 3sg.NOM fish here see.PAST", "r296_3sg_here_water_fauna_see_kuyu", ["nyulu", "kuyu", "yaluy", "nyajin"]),
    row(24, "He saw the stingray here.", "Nyulu yawu yaluy nyajin.", "nyulu yawu yaluy nyajin | 3sg.NOM stingray here see.PAST", "r296_3sg_here_water_fauna_see_yawu", ["nyulu", "yawu", "yaluy", "nyajin"]),
    row(25, "He saw the barramundi here.", "Nyulu judi yaluy nyajin.", "nyulu judi yaluy nyajin | 3sg.NOM barramundi here see.PAST", "r296_3sg_here_water_fauna_see_judi", ["nyulu", "judi", "yaluy", "nyajin"]),
    row(26, "He saw the mullet here.", "Nyulu ngalkun yaluy nyajin.", "nyulu ngalkun yaluy nyajin | 3sg.NOM mullet here see.PAST", "r296_3sg_here_water_fauna_see_ngalkun", ["nyulu", "ngalkun", "yaluy", "nyajin"]),
    row(27, "He saw the freshwater eel here.", "Nyulu kubarr yaluy nyajin.", "nyulu kubarr yaluy nyajin | 3sg.NOM freshwater.eel here see.PAST", "r296_3sg_here_water_fauna_see_kubarr", ["nyulu", "kubarr", "yaluy", "nyajin"]),
    row(28, "He saw the mudcrab here.", "Nyulu kiju yaluy nyajin.", "nyulu kiju yaluy nyajin | 3sg.NOM mudcrab here see.PAST", "r296_3sg_here_water_fauna_see_kiju", ["nyulu", "kiju", "yaluy", "nyajin"]),
    row(29, "He saw the prawn here.", "Nyulu wakal yaluy nyajin.", "nyulu wakal yaluy nyajin | 3sg.NOM prawn here see.PAST", "r296_3sg_here_water_fauna_see_wakal", ["nyulu", "wakal", "yaluy", "nyajin"]),
    row(30, "He saw the oyster here.", "Nyulu julul yaluy nyajin.", "nyulu julul yaluy nyajin | 3sg.NOM oyster here see.PAST", "r296_3sg_here_water_fauna_see_julul", ["nyulu", "julul", "yaluy", "nyajin"]),
    row(31, "They two saw the sea turtle there.", "Bula ngawiya yinyay nyajin.", "bula ngawiya yinyay nyajin | 3du.NOM sea.turtle there see.PAST", "r296_3du_there_water_fauna_see_ngawiya", ["bula", "ngawiya", "yinyay", "nyajin"]),
    row(32, "They two saw the freshwater turtle there.", "Bula ngujay yinyay nyajin.", "bula ngujay yinyay nyajin | 3du.NOM freshwater.turtle there see.PAST", "r296_3du_there_water_fauna_see_ngujay", ["bula", "ngujay", "yinyay", "nyajin"]),
    row(33, "They two saw the fish there.", "Bula kuyu yinyay nyajin.", "bula kuyu yinyay nyajin | 3du.NOM fish there see.PAST", "r296_3du_there_water_fauna_see_kuyu", ["bula", "kuyu", "yinyay", "nyajin"]),
    row(34, "They two saw the stingray there.", "Bula yawu yinyay nyajin.", "bula yawu yinyay nyajin | 3du.NOM stingray there see.PAST", "r296_3du_there_water_fauna_see_yawu", ["bula", "yawu", "yinyay", "nyajin"]),
    row(35, "They two saw the barramundi there.", "Bula judi yinyay nyajin.", "bula judi yinyay nyajin | 3du.NOM barramundi there see.PAST", "r296_3du_there_water_fauna_see_judi", ["bula", "judi", "yinyay", "nyajin"]),
    row(36, "They two saw the mullet there.", "Bula ngalkun yinyay nyajin.", "bula ngalkun yinyay nyajin | 3du.NOM mullet there see.PAST", "r296_3du_there_water_fauna_see_ngalkun", ["bula", "ngalkun", "yinyay", "nyajin"]),
    row(37, "They two saw the freshwater eel there.", "Bula kubarr yinyay nyajin.", "bula kubarr yinyay nyajin | 3du.NOM freshwater.eel there see.PAST", "r296_3du_there_water_fauna_see_kubarr", ["bula", "kubarr", "yinyay", "nyajin"]),
    row(38, "They two saw the mudcrab there.", "Bula kiju yinyay nyajin.", "bula kiju yinyay nyajin | 3du.NOM mudcrab there see.PAST", "r296_3du_there_water_fauna_see_kiju", ["bula", "kiju", "yinyay", "nyajin"]),
    row(39, "They two saw the prawn there.", "Bula wakal yinyay nyajin.", "bula wakal yinyay nyajin | 3du.NOM prawn there see.PAST", "r296_3du_there_water_fauna_see_wakal", ["bula", "wakal", "yinyay", "nyajin"]),
    row(40, "They two saw the oyster there.", "Bula julul yinyay nyajin.", "bula julul yinyay nyajin | 3du.NOM oyster there see.PAST", "r296_3du_there_water_fauna_see_julul", ["bula", "julul", "yinyay", "nyajin"]),
    row(41, "They saw the sea turtle here.", "Jana ngawiya yaluy nyajin.", "jana ngawiya yaluy nyajin | 3pl.NOM sea.turtle here see.PAST", "r296_3pl_here_water_fauna_see_ngawiya", ["jana", "ngawiya", "yaluy", "nyajin"]),
    row(42, "They saw the freshwater turtle here.", "Jana ngujay yaluy nyajin.", "jana ngujay yaluy nyajin | 3pl.NOM freshwater.turtle here see.PAST", "r296_3pl_here_water_fauna_see_ngujay", ["jana", "ngujay", "yaluy", "nyajin"]),
    row(43, "They saw the fish here.", "Jana kuyu yaluy nyajin.", "jana kuyu yaluy nyajin | 3pl.NOM fish here see.PAST", "r296_3pl_here_water_fauna_see_kuyu", ["jana", "kuyu", "yaluy", "nyajin"]),
    row(44, "They saw the stingray here.", "Jana yawu yaluy nyajin.", "jana yawu yaluy nyajin | 3pl.NOM stingray here see.PAST", "r296_3pl_here_water_fauna_see_yawu", ["jana", "yawu", "yaluy", "nyajin"]),
    row(45, "They saw the barramundi here.", "Jana judi yaluy nyajin.", "jana judi yaluy nyajin | 3pl.NOM barramundi here see.PAST", "r296_3pl_here_water_fauna_see_judi", ["jana", "judi", "yaluy", "nyajin"]),
    row(46, "They saw the mullet here.", "Jana ngalkun yaluy nyajin.", "jana ngalkun yaluy nyajin | 3pl.NOM mullet here see.PAST", "r296_3pl_here_water_fauna_see_ngalkun", ["jana", "ngalkun", "yaluy", "nyajin"]),
    row(47, "They saw the freshwater eel here.", "Jana kubarr yaluy nyajin.", "jana kubarr yaluy nyajin | 3pl.NOM freshwater.eel here see.PAST", "r296_3pl_here_water_fauna_see_kubarr", ["jana", "kubarr", "yaluy", "nyajin"]),
    row(48, "They saw the mudcrab here.", "Jana kiju yaluy nyajin.", "jana kiju yaluy nyajin | 3pl.NOM mudcrab here see.PAST", "r296_3pl_here_water_fauna_see_kiju", ["jana", "kiju", "yaluy", "nyajin"]),
    row(49, "They saw the prawn here.", "Jana wakal yaluy nyajin.", "jana wakal yaluy nyajin | 3pl.NOM prawn here see.PAST", "r296_3pl_here_water_fauna_see_wakal", ["jana", "wakal", "yaluy", "nyajin"]),
    row(50, "They saw the oyster here.", "Jana julul yaluy nyajin.", "jana julul yaluy nyajin | 3pl.NOM oyster here see.PAST", "r296_3pl_here_water_fauna_see_julul", ["jana", "julul", "yaluy", "nyajin"]),
]


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"row count {len(ROWS)} != 50")
    if [r[0] for r in ROWS] != list(range(1, 51)):
        issues.append("sequence is not 1..50")
    kukus = [r[2] for r in ROWS]
    if len(set(kukus)) != len(kukus):
        issues.append("duplicate Kuku surface inside batch")
    for seq, english, kuku, _analysis, frame, _tier, words_json, loans_json, _evidence, _confidence in ROWS:
        words = json.loads(words_json)
        loans = json.loads(loans_json)
        lower_kuku = kuku.lower()
        lower_english = english.lower()
        if loans:
            issues.append(f"{seq}: loans used {loans}")
        denied = sorted({w for w in DENY_KUKU if re.search(rf"(^|\\s){re.escape(w)}([\\s\\.]|$)", lower_kuku)})
        if denied:
            issues.append(f"{seq}: denied Kuku forms {denied}")
        denied_english = [term for term in DENY_ENGLISH if re.search(rf"\\b{re.escape(term.strip())}\\b", lower_english)]
        if denied_english:
            issues.append(f"{seq}: denied English drift {denied_english}")
        target_hits = [w for w in TARGET_ORDER if w in words]
        if len(target_hits) != 1:
            issues.append(f"{seq}: target hits {target_hits}")
        if len(words) != 4:
            issues.append(f"{seq}: expected 4 words, got {words}")
        if "nyajin" not in words or not lower_kuku.endswith(" nyajin."):
            issues.append(f"{seq}: missing final nyajin")
        if "nyajil" in lower_kuku:
            issues.append(f"{seq}: nonpast nyajil leakage")
        if len([w for w in ("yaluy", "yinyay") if w in words]) != 1:
            issues.append(f"{seq}: demonstrative problem {words}")
        expected_pronoun, expected_demo = FRAME_SPECS[(seq - 1) // 10]
        if words[0] != expected_pronoun:
            issues.append(f"{seq}: expected pronoun {expected_pronoun}, got {words[0]}")
        if words[2] != expected_demo:
            issues.append(f"{seq}: expected demonstrative {expected_demo}, got {words[2]}")
        if words[1] != TARGET_ORDER[(seq - 1) % 10]:
            issues.append(f"{seq}: target order mismatch {words[1]}")
        if words[3] != "nyajin":
            issues.append(f"{seq}: word 4 is not nyajin {words[3]}")
        if lower_kuku.rstrip(".") != " ".join(words):
            issues.append(f"{seq}: Kuku does not match words_used {words}")
        if not frame.startswith("r296_"):
            issues.append(f"{seq}: frame not r296 {frame}")
    return issues


def count_words(db: sqlite3.Connection, words: list[str]) -> dict[str, int]:
    return {
        word: db.execute(
            """
            SELECT COUNT(*)
            FROM sentences s
            WHERE s.status IN ('accepted','revised')
              AND EXISTS (SELECT 1 FROM json_each(s.words_used) WHERE value=?)
            """,
            (word,),
        ).fetchone()[0]
        for word in words
    }


def main() -> int:
    issues = scan_static()
    if issues:
        for issue in issues:
            print(issue)
        raise SystemExit(1)

    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    if db.execute("SELECT 1 FROM batches WHERE label=?", (LABEL,)).fetchone():
        raise SystemExit(f"{LABEL} already exists")
    collisions = []
    for _seq, _english, kuku, *_rest in ROWS:
        existing = db.execute(
            """
            SELECT b.label, s.seq, s.status
            FROM sentences s
            JOIN batches b ON b.id=s.batch_id
            WHERE lower(s.kuku)=lower(?) AND s.status!='rejected'
            """,
            (kuku,),
        ).fetchall()
        if existing:
            collisions.append((kuku, existing))
    if collisions:
        raise SystemExit(f"duplicate preflight failed: {collisions}")

    target_counts = count_words(db, TARGET_ORDER)
    support_counts = count_words(db, ["ngayu", "yundu", "nyulu", "bula", "jana", "yaluy", "yinyay", "nyajin"])
    verified_before, words_before = db.execute(
        """
        SELECT COUNT(*), SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()

    notes = (
        "VISIBLE WATER-FAUNA SINGULAR/THIRD PAST PERCEPTION SWEEP AFTER RULE 295 (Rule 296). "
        "50 under-review rows over ten checked visible target heads: ngawiya sea turtle, ngujay freshwater turtle, "
        "kuyu fish, yawu stingray, judi barramundi, ngalkun mullet, kubarr freshwater eel, kiju mudcrab, wakal prawn, "
        "and julul oyster. SUPPORT: bare nominative ngayu, yundu, nyulu, bula, and jana, plus yaluy/yinyay and nyajin. "
        "Only bare visible object past perception/reference rows are opened; catching, spearing, hunting, cooking, "
        "eating, bait, net, hook, danger, ecology, place/story, target case, pronoun case, demonstrative case, compounds, "
        "productive reduplication, nonpast/purposive/reduplicated perception drift, and support inflection remain closed."
    )
    cur = db.execute(
        "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
        (LABEL, "Rule 296 under review", "operator-guide-2026-07-09", notes, NOW),
    )
    batch_id = cur.lastrowid
    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used,
          evidence, status, confidence, rights_status, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (
                batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used,
                evidence, "under_review", confidence,
                "project_approved_synthetic_pending_elder_verification", "claude", NOW, NOW,
            )
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    record_event(db, batch_label=LABEL, phase="source", event_type="source-readback", actor="claude-main", detail="Reread core dictionary-derived lexicon lines 744-759 for ten visible water-fauna targets and Patz pronoun, demonstrative, and nyaji-ny past support before authoring Rule 296.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="past-counterpart-scope", actor="claude-main", detail="Selected the sourced past counterpart to Rule 295's visible water-fauna singular/third-person nonpast perception bands. The batch uses the same zero-collision target set and does not open catching, spearing, hunting, cooking, eating, ecology, danger, or source-prose semantics.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="coverage-audit", actor="claude-main", detail=f"Token-aware accepted/revised coverage before banking from words_used JSON: targets={target_counts}; support={support_counts}.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="duplicate-preflight", actor="claude-main", detail="Final 50 Rule 296 visible water-fauna singular/third past surfaces returned no accepted, revised, or under-review collisions over the Rule 295 target set.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main", detail="Static guard passed: 50 explicit hand-authored rows, one target each, bare nominative singular/third pronoun bands, bare yaluy/yinyay, final nyajin, no loans, no denied Kuku forms, and no catch/spear/cook/eat/ecology/case/compound drift.", command="python3 -m py_compile batch_scripts/bank_338.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_338; print(bank_338.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_338.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 296 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_338.py", output_excerpt=f"banked batch-338: 50 rows under_review; verified_before={verified_before}; kuku_words_before={words_before}", artifact_path=PROCESS_LOG, created_at=NOW)
    db.commit()
    print("banked batch-338: 50 rows under_review")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
