#!/usr/bin/env python3
"""Bank batch-340: Rule 298 visible water-fauna non-singular 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-340"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-340-visible-water-fauna-nonsingular-past-perception-after-rule297-process.md"

TARGET_EVIDENCE = {
    "ngawiya": "Core lexicon line 744 gives ngawiya as 'sea turtle', neutral, with a hunted-food note. Rule 298 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 298 selects visible freshwater-turtle reference only.",
    "kuyu": "Core lexicon line 751 gives kuyu as 'fish', neutral as food/object. Rule 298 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 298 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 298 selects visible barramundi reference only.",
    "ngalkun": "Core lexicon line 755 gives ngalkun as 'mullet', neutral. Rule 298 selects visible mullet reference only.",
    "kubarr": "Core lexicon line 756 gives kubarr as 'big black freshwater eel', neutral. Rule 298 selects visible freshwater-eel reference only and does not open colour/property rows.",
    "kiju": "Core lexicon line 757 gives kiju as 'mudcrab', neutral. Rule 298 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 298 selects visible prawn reference only and leaves lobster alternation, catching, cooking, and eating rows closed.",
    "julul": "Core lexicon line 759 gives julul as 'oyster', neutral. Rule 298 selects visible oyster reference only and leaves gathering, eating, and shore/ecology rows closed.",
}

SUPPORT_EVIDENCE = (
    "Patz pronoun tables source bare nominative ngali, ngaliny, yubal, yurra, and ngana; local-demonstrative lines "
    "source yaluy 'here' and yinyay 'there'; Patz examples source nyaji-ny 'see-PAST', and the tense section "
    "sources past -ny. Rule 298 uses corpus-conventional nyajin as the past visual-perception surface."
)

TARGET_ORDER = ["ngawiya", "ngujay", "kuyu", "yawu", "judi", "ngalkun", "kubarr", "kiju", "wakal", "julul"]
FRAME_SPECS = [
    ("ngali", "yaluy"),
    ("ngaliny", "yinyay"),
    ("yubal", "yaluy"),
    ("yurra", "yinyay"),
    ("ngana", "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",
    "ngalingan", "ngalinka", "ngalinda", "ngalindamuny", "ngalinji", "ngalinga",
    "ngalinyan", "ngalinyanka", "ngalinyanda", "ngalinyandamuny", "ngalinyanji", "ngalinyanga",
    "yubalan", "yubalanka", "yubalanda", "yubalandamuny", "yubalanji", "yubalanga",
    "yurrangan", "yurranka", "yurranda", "yurrandamuny", "yurranji", "yurranga",
    "nganangan", "ngananka", "ngananda", "nganandamuny", "ngananji", "ngananga",
    "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, "We two, not you, saw the sea turtle here.", "Ngali ngawiya yaluy nyajin.", "ngali ngawiya yaluy nyajin | 1du.EXCL.NOM sea.turtle here see.PAST", "r298_1du_excl_here_water_fauna_saw_ngawiya", ["ngali", "ngawiya", "yaluy", "nyajin"]),
    row(2, "We two, not you, saw the freshwater turtle here.", "Ngali ngujay yaluy nyajin.", "ngali ngujay yaluy nyajin | 1du.EXCL.NOM freshwater.turtle here see.PAST", "r298_1du_excl_here_water_fauna_saw_ngujay", ["ngali", "ngujay", "yaluy", "nyajin"]),
    row(3, "We two, not you, saw the fish here.", "Ngali kuyu yaluy nyajin.", "ngali kuyu yaluy nyajin | 1du.EXCL.NOM fish here see.PAST", "r298_1du_excl_here_water_fauna_saw_kuyu", ["ngali", "kuyu", "yaluy", "nyajin"]),
    row(4, "We two, not you, saw the stingray here.", "Ngali yawu yaluy nyajin.", "ngali yawu yaluy nyajin | 1du.EXCL.NOM stingray here see.PAST", "r298_1du_excl_here_water_fauna_saw_yawu", ["ngali", "yawu", "yaluy", "nyajin"]),
    row(5, "We two, not you, saw the barramundi here.", "Ngali judi yaluy nyajin.", "ngali judi yaluy nyajin | 1du.EXCL.NOM barramundi here see.PAST", "r298_1du_excl_here_water_fauna_saw_judi", ["ngali", "judi", "yaluy", "nyajin"]),
    row(6, "We two, not you, saw the mullet here.", "Ngali ngalkun yaluy nyajin.", "ngali ngalkun yaluy nyajin | 1du.EXCL.NOM mullet here see.PAST", "r298_1du_excl_here_water_fauna_saw_ngalkun", ["ngali", "ngalkun", "yaluy", "nyajin"]),
    row(7, "We two, not you, saw the freshwater eel here.", "Ngali kubarr yaluy nyajin.", "ngali kubarr yaluy nyajin | 1du.EXCL.NOM freshwater.eel here see.PAST", "r298_1du_excl_here_water_fauna_saw_kubarr", ["ngali", "kubarr", "yaluy", "nyajin"]),
    row(8, "We two, not you, saw the mudcrab here.", "Ngali kiju yaluy nyajin.", "ngali kiju yaluy nyajin | 1du.EXCL.NOM mudcrab here see.PAST", "r298_1du_excl_here_water_fauna_saw_kiju", ["ngali", "kiju", "yaluy", "nyajin"]),
    row(9, "We two, not you, saw the prawn here.", "Ngali wakal yaluy nyajin.", "ngali wakal yaluy nyajin | 1du.EXCL.NOM prawn here see.PAST", "r298_1du_excl_here_water_fauna_saw_wakal", ["ngali", "wakal", "yaluy", "nyajin"]),
    row(10, "We two, not you, saw the oyster here.", "Ngali julul yaluy nyajin.", "ngali julul yaluy nyajin | 1du.EXCL.NOM oyster here see.PAST", "r298_1du_excl_here_water_fauna_saw_julul", ["ngali", "julul", "yaluy", "nyajin"]),
    row(11, "You and I saw the sea turtle there.", "Ngaliny ngawiya yinyay nyajin.", "ngaliny ngawiya yinyay nyajin | 1du.INCL.NOM sea.turtle there see.PAST", "r298_1du_incl_there_water_fauna_saw_ngawiya", ["ngaliny", "ngawiya", "yinyay", "nyajin"]),
    row(12, "You and I saw the freshwater turtle there.", "Ngaliny ngujay yinyay nyajin.", "ngaliny ngujay yinyay nyajin | 1du.INCL.NOM freshwater.turtle there see.PAST", "r298_1du_incl_there_water_fauna_saw_ngujay", ["ngaliny", "ngujay", "yinyay", "nyajin"]),
    row(13, "You and I saw the fish there.", "Ngaliny kuyu yinyay nyajin.", "ngaliny kuyu yinyay nyajin | 1du.INCL.NOM fish there see.PAST", "r298_1du_incl_there_water_fauna_saw_kuyu", ["ngaliny", "kuyu", "yinyay", "nyajin"]),
    row(14, "You and I saw the stingray there.", "Ngaliny yawu yinyay nyajin.", "ngaliny yawu yinyay nyajin | 1du.INCL.NOM stingray there see.PAST", "r298_1du_incl_there_water_fauna_saw_yawu", ["ngaliny", "yawu", "yinyay", "nyajin"]),
    row(15, "You and I saw the barramundi there.", "Ngaliny judi yinyay nyajin.", "ngaliny judi yinyay nyajin | 1du.INCL.NOM barramundi there see.PAST", "r298_1du_incl_there_water_fauna_saw_judi", ["ngaliny", "judi", "yinyay", "nyajin"]),
    row(16, "You and I saw the mullet there.", "Ngaliny ngalkun yinyay nyajin.", "ngaliny ngalkun yinyay nyajin | 1du.INCL.NOM mullet there see.PAST", "r298_1du_incl_there_water_fauna_saw_ngalkun", ["ngaliny", "ngalkun", "yinyay", "nyajin"]),
    row(17, "You and I saw the freshwater eel there.", "Ngaliny kubarr yinyay nyajin.", "ngaliny kubarr yinyay nyajin | 1du.INCL.NOM freshwater.eel there see.PAST", "r298_1du_incl_there_water_fauna_saw_kubarr", ["ngaliny", "kubarr", "yinyay", "nyajin"]),
    row(18, "You and I saw the mudcrab there.", "Ngaliny kiju yinyay nyajin.", "ngaliny kiju yinyay nyajin | 1du.INCL.NOM mudcrab there see.PAST", "r298_1du_incl_there_water_fauna_saw_kiju", ["ngaliny", "kiju", "yinyay", "nyajin"]),
    row(19, "You and I saw the prawn there.", "Ngaliny wakal yinyay nyajin.", "ngaliny wakal yinyay nyajin | 1du.INCL.NOM prawn there see.PAST", "r298_1du_incl_there_water_fauna_saw_wakal", ["ngaliny", "wakal", "yinyay", "nyajin"]),
    row(20, "You and I saw the oyster there.", "Ngaliny julul yinyay nyajin.", "ngaliny julul yinyay nyajin | 1du.INCL.NOM oyster there see.PAST", "r298_1du_incl_there_water_fauna_saw_julul", ["ngaliny", "julul", "yinyay", "nyajin"]),
    row(21, "You two saw the sea turtle here.", "Yubal ngawiya yaluy nyajin.", "yubal ngawiya yaluy nyajin | 2du.NOM sea.turtle here see.PAST", "r298_2du_here_water_fauna_saw_ngawiya", ["yubal", "ngawiya", "yaluy", "nyajin"]),
    row(22, "You two saw the freshwater turtle here.", "Yubal ngujay yaluy nyajin.", "yubal ngujay yaluy nyajin | 2du.NOM freshwater.turtle here see.PAST", "r298_2du_here_water_fauna_saw_ngujay", ["yubal", "ngujay", "yaluy", "nyajin"]),
    row(23, "You two saw the fish here.", "Yubal kuyu yaluy nyajin.", "yubal kuyu yaluy nyajin | 2du.NOM fish here see.PAST", "r298_2du_here_water_fauna_saw_kuyu", ["yubal", "kuyu", "yaluy", "nyajin"]),
    row(24, "You two saw the stingray here.", "Yubal yawu yaluy nyajin.", "yubal yawu yaluy nyajin | 2du.NOM stingray here see.PAST", "r298_2du_here_water_fauna_saw_yawu", ["yubal", "yawu", "yaluy", "nyajin"]),
    row(25, "You two saw the barramundi here.", "Yubal judi yaluy nyajin.", "yubal judi yaluy nyajin | 2du.NOM barramundi here see.PAST", "r298_2du_here_water_fauna_saw_judi", ["yubal", "judi", "yaluy", "nyajin"]),
    row(26, "You two saw the mullet here.", "Yubal ngalkun yaluy nyajin.", "yubal ngalkun yaluy nyajin | 2du.NOM mullet here see.PAST", "r298_2du_here_water_fauna_saw_ngalkun", ["yubal", "ngalkun", "yaluy", "nyajin"]),
    row(27, "You two saw the freshwater eel here.", "Yubal kubarr yaluy nyajin.", "yubal kubarr yaluy nyajin | 2du.NOM freshwater.eel here see.PAST", "r298_2du_here_water_fauna_saw_kubarr", ["yubal", "kubarr", "yaluy", "nyajin"]),
    row(28, "You two saw the mudcrab here.", "Yubal kiju yaluy nyajin.", "yubal kiju yaluy nyajin | 2du.NOM mudcrab here see.PAST", "r298_2du_here_water_fauna_saw_kiju", ["yubal", "kiju", "yaluy", "nyajin"]),
    row(29, "You two saw the prawn here.", "Yubal wakal yaluy nyajin.", "yubal wakal yaluy nyajin | 2du.NOM prawn here see.PAST", "r298_2du_here_water_fauna_saw_wakal", ["yubal", "wakal", "yaluy", "nyajin"]),
    row(30, "You two saw the oyster here.", "Yubal julul yaluy nyajin.", "yubal julul yaluy nyajin | 2du.NOM oyster here see.PAST", "r298_2du_here_water_fauna_saw_julul", ["yubal", "julul", "yaluy", "nyajin"]),
    row(31, "You all saw the sea turtle there.", "Yurra ngawiya yinyay nyajin.", "yurra ngawiya yinyay nyajin | 2pl.NOM sea.turtle there see.PAST", "r298_2pl_there_water_fauna_saw_ngawiya", ["yurra", "ngawiya", "yinyay", "nyajin"]),
    row(32, "You all saw the freshwater turtle there.", "Yurra ngujay yinyay nyajin.", "yurra ngujay yinyay nyajin | 2pl.NOM freshwater.turtle there see.PAST", "r298_2pl_there_water_fauna_saw_ngujay", ["yurra", "ngujay", "yinyay", "nyajin"]),
    row(33, "You all saw the fish there.", "Yurra kuyu yinyay nyajin.", "yurra kuyu yinyay nyajin | 2pl.NOM fish there see.PAST", "r298_2pl_there_water_fauna_saw_kuyu", ["yurra", "kuyu", "yinyay", "nyajin"]),
    row(34, "You all saw the stingray there.", "Yurra yawu yinyay nyajin.", "yurra yawu yinyay nyajin | 2pl.NOM stingray there see.PAST", "r298_2pl_there_water_fauna_saw_yawu", ["yurra", "yawu", "yinyay", "nyajin"]),
    row(35, "You all saw the barramundi there.", "Yurra judi yinyay nyajin.", "yurra judi yinyay nyajin | 2pl.NOM barramundi there see.PAST", "r298_2pl_there_water_fauna_saw_judi", ["yurra", "judi", "yinyay", "nyajin"]),
    row(36, "You all saw the mullet there.", "Yurra ngalkun yinyay nyajin.", "yurra ngalkun yinyay nyajin | 2pl.NOM mullet there see.PAST", "r298_2pl_there_water_fauna_saw_ngalkun", ["yurra", "ngalkun", "yinyay", "nyajin"]),
    row(37, "You all saw the freshwater eel there.", "Yurra kubarr yinyay nyajin.", "yurra kubarr yinyay nyajin | 2pl.NOM freshwater.eel there see.PAST", "r298_2pl_there_water_fauna_saw_kubarr", ["yurra", "kubarr", "yinyay", "nyajin"]),
    row(38, "You all saw the mudcrab there.", "Yurra kiju yinyay nyajin.", "yurra kiju yinyay nyajin | 2pl.NOM mudcrab there see.PAST", "r298_2pl_there_water_fauna_saw_kiju", ["yurra", "kiju", "yinyay", "nyajin"]),
    row(39, "You all saw the prawn there.", "Yurra wakal yinyay nyajin.", "yurra wakal yinyay nyajin | 2pl.NOM prawn there see.PAST", "r298_2pl_there_water_fauna_saw_wakal", ["yurra", "wakal", "yinyay", "nyajin"]),
    row(40, "You all saw the oyster there.", "Yurra julul yinyay nyajin.", "yurra julul yinyay nyajin | 2pl.NOM oyster there see.PAST", "r298_2pl_there_water_fauna_saw_julul", ["yurra", "julul", "yinyay", "nyajin"]),
    row(41, "We saw the sea turtle here.", "Ngana ngawiya yaluy nyajin.", "ngana ngawiya yaluy nyajin | 1pl.INCL.NOM sea.turtle here see.PAST", "r298_1pl_incl_here_water_fauna_saw_ngawiya", ["ngana", "ngawiya", "yaluy", "nyajin"]),
    row(42, "We saw the freshwater turtle here.", "Ngana ngujay yaluy nyajin.", "ngana ngujay yaluy nyajin | 1pl.INCL.NOM freshwater.turtle here see.PAST", "r298_1pl_incl_here_water_fauna_saw_ngujay", ["ngana", "ngujay", "yaluy", "nyajin"]),
    row(43, "We saw the fish here.", "Ngana kuyu yaluy nyajin.", "ngana kuyu yaluy nyajin | 1pl.INCL.NOM fish here see.PAST", "r298_1pl_incl_here_water_fauna_saw_kuyu", ["ngana", "kuyu", "yaluy", "nyajin"]),
    row(44, "We saw the stingray here.", "Ngana yawu yaluy nyajin.", "ngana yawu yaluy nyajin | 1pl.INCL.NOM stingray here see.PAST", "r298_1pl_incl_here_water_fauna_saw_yawu", ["ngana", "yawu", "yaluy", "nyajin"]),
    row(45, "We saw the barramundi here.", "Ngana judi yaluy nyajin.", "ngana judi yaluy nyajin | 1pl.INCL.NOM barramundi here see.PAST", "r298_1pl_incl_here_water_fauna_saw_judi", ["ngana", "judi", "yaluy", "nyajin"]),
    row(46, "We saw the mullet here.", "Ngana ngalkun yaluy nyajin.", "ngana ngalkun yaluy nyajin | 1pl.INCL.NOM mullet here see.PAST", "r298_1pl_incl_here_water_fauna_saw_ngalkun", ["ngana", "ngalkun", "yaluy", "nyajin"]),
    row(47, "We saw the freshwater eel here.", "Ngana kubarr yaluy nyajin.", "ngana kubarr yaluy nyajin | 1pl.INCL.NOM freshwater.eel here see.PAST", "r298_1pl_incl_here_water_fauna_saw_kubarr", ["ngana", "kubarr", "yaluy", "nyajin"]),
    row(48, "We saw the mudcrab here.", "Ngana kiju yaluy nyajin.", "ngana kiju yaluy nyajin | 1pl.INCL.NOM mudcrab here see.PAST", "r298_1pl_incl_here_water_fauna_saw_kiju", ["ngana", "kiju", "yaluy", "nyajin"]),
    row(49, "We saw the prawn here.", "Ngana wakal yaluy nyajin.", "ngana wakal yaluy nyajin | 1pl.INCL.NOM prawn here see.PAST", "r298_1pl_incl_here_water_fauna_saw_wakal", ["ngana", "wakal", "yaluy", "nyajin"]),
    row(50, "We saw the oyster here.", "Ngana julul yaluy nyajin.", "ngana julul yaluy nyajin | 1pl.INCL.NOM oyster here see.PAST", "r298_1pl_incl_here_water_fauna_saw_julul", ["ngana", "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("r298_"):
            issues.append(f"{seq}: frame not r298 {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, ["ngali", "ngaliny", "yubal", "yurra", "ngana", "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 NON-SINGULAR PAST PERCEPTION SWEEP AFTER RULE 297 (Rule 298). "
        "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 ngali, ngaliny, yubal, yurra, and ngana, 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 298 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 298.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="nonsingular-past-scope", actor="claude-main", detail="Selected a sourced non-singular past counterpart to Rule 297's visible water-fauna non-singular nonpast band and Rules 295-296's singular/third bands. The batch uses ngali, ngaliny, yubal, yurra, and ngana with nyajin, 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 298 visible water-fauna non-singular past surfaces returned no accepted, revised, or under-review collisions over the Rule 295-297 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 non-singular nominative 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_340.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_340; print(bank_340.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_340.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 298 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_340.py", output_excerpt=f"banked batch-340: 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-340: 50 rows under_review")
    return 0


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