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

TARGET_EVIDENCE = {
    "ngawiya": "Core lexicon line 744 gives ngawiya as 'sea turtle', neutral, with a hunted-food note. Rule 297 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 297 selects visible freshwater-turtle reference only.",
    "kuyu": "Core lexicon line 751 gives kuyu as 'fish', neutral as food/object. Rule 297 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 297 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 297 selects visible barramundi reference only.",
    "ngalkun": "Core lexicon line 755 gives ngalkun as 'mullet', neutral. Rule 297 selects visible mullet reference only.",
    "kubarr": "Core lexicon line 756 gives kubarr as 'big black freshwater eel', neutral. Rule 297 selects visible freshwater-eel reference only and does not open colour/property rows.",
    "kiju": "Core lexicon line 757 gives kiju as 'mudcrab', neutral. Rule 297 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 297 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 297 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 section 3.8.3.2 sources nyaji-l 'see', and the tense section "
    "sources nonpast -l. Rule 297 uses corpus-conventional nyajil as the nonpast 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",
    "nyajin", "nyaji-ny", "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, see the sea turtle here.", "Ngali ngawiya yaluy nyajil.", "ngali ngawiya yaluy nyajil | 1du.EXCL.NOM sea.turtle here see.NONPAST", "r297_1du_excl_here_water_fauna_see_ngawiya", ["ngali", "ngawiya", "yaluy", "nyajil"]),
    row(2, "We two, not you, see the freshwater turtle here.", "Ngali ngujay yaluy nyajil.", "ngali ngujay yaluy nyajil | 1du.EXCL.NOM freshwater.turtle here see.NONPAST", "r297_1du_excl_here_water_fauna_see_ngujay", ["ngali", "ngujay", "yaluy", "nyajil"]),
    row(3, "We two, not you, see the fish here.", "Ngali kuyu yaluy nyajil.", "ngali kuyu yaluy nyajil | 1du.EXCL.NOM fish here see.NONPAST", "r297_1du_excl_here_water_fauna_see_kuyu", ["ngali", "kuyu", "yaluy", "nyajil"]),
    row(4, "We two, not you, see the stingray here.", "Ngali yawu yaluy nyajil.", "ngali yawu yaluy nyajil | 1du.EXCL.NOM stingray here see.NONPAST", "r297_1du_excl_here_water_fauna_see_yawu", ["ngali", "yawu", "yaluy", "nyajil"]),
    row(5, "We two, not you, see the barramundi here.", "Ngali judi yaluy nyajil.", "ngali judi yaluy nyajil | 1du.EXCL.NOM barramundi here see.NONPAST", "r297_1du_excl_here_water_fauna_see_judi", ["ngali", "judi", "yaluy", "nyajil"]),
    row(6, "We two, not you, see the mullet here.", "Ngali ngalkun yaluy nyajil.", "ngali ngalkun yaluy nyajil | 1du.EXCL.NOM mullet here see.NONPAST", "r297_1du_excl_here_water_fauna_see_ngalkun", ["ngali", "ngalkun", "yaluy", "nyajil"]),
    row(7, "We two, not you, see the freshwater eel here.", "Ngali kubarr yaluy nyajil.", "ngali kubarr yaluy nyajil | 1du.EXCL.NOM freshwater.eel here see.NONPAST", "r297_1du_excl_here_water_fauna_see_kubarr", ["ngali", "kubarr", "yaluy", "nyajil"]),
    row(8, "We two, not you, see the mudcrab here.", "Ngali kiju yaluy nyajil.", "ngali kiju yaluy nyajil | 1du.EXCL.NOM mudcrab here see.NONPAST", "r297_1du_excl_here_water_fauna_see_kiju", ["ngali", "kiju", "yaluy", "nyajil"]),
    row(9, "We two, not you, see the prawn here.", "Ngali wakal yaluy nyajil.", "ngali wakal yaluy nyajil | 1du.EXCL.NOM prawn here see.NONPAST", "r297_1du_excl_here_water_fauna_see_wakal", ["ngali", "wakal", "yaluy", "nyajil"]),
    row(10, "We two, not you, see the oyster here.", "Ngali julul yaluy nyajil.", "ngali julul yaluy nyajil | 1du.EXCL.NOM oyster here see.NONPAST", "r297_1du_excl_here_water_fauna_see_julul", ["ngali", "julul", "yaluy", "nyajil"]),
    row(11, "You and I see the sea turtle there.", "Ngaliny ngawiya yinyay nyajil.", "ngaliny ngawiya yinyay nyajil | 1du.INCL.NOM sea.turtle there see.NONPAST", "r297_1du_incl_there_water_fauna_see_ngawiya", ["ngaliny", "ngawiya", "yinyay", "nyajil"]),
    row(12, "You and I see the freshwater turtle there.", "Ngaliny ngujay yinyay nyajil.", "ngaliny ngujay yinyay nyajil | 1du.INCL.NOM freshwater.turtle there see.NONPAST", "r297_1du_incl_there_water_fauna_see_ngujay", ["ngaliny", "ngujay", "yinyay", "nyajil"]),
    row(13, "You and I see the fish there.", "Ngaliny kuyu yinyay nyajil.", "ngaliny kuyu yinyay nyajil | 1du.INCL.NOM fish there see.NONPAST", "r297_1du_incl_there_water_fauna_see_kuyu", ["ngaliny", "kuyu", "yinyay", "nyajil"]),
    row(14, "You and I see the stingray there.", "Ngaliny yawu yinyay nyajil.", "ngaliny yawu yinyay nyajil | 1du.INCL.NOM stingray there see.NONPAST", "r297_1du_incl_there_water_fauna_see_yawu", ["ngaliny", "yawu", "yinyay", "nyajil"]),
    row(15, "You and I see the barramundi there.", "Ngaliny judi yinyay nyajil.", "ngaliny judi yinyay nyajil | 1du.INCL.NOM barramundi there see.NONPAST", "r297_1du_incl_there_water_fauna_see_judi", ["ngaliny", "judi", "yinyay", "nyajil"]),
    row(16, "You and I see the mullet there.", "Ngaliny ngalkun yinyay nyajil.", "ngaliny ngalkun yinyay nyajil | 1du.INCL.NOM mullet there see.NONPAST", "r297_1du_incl_there_water_fauna_see_ngalkun", ["ngaliny", "ngalkun", "yinyay", "nyajil"]),
    row(17, "You and I see the freshwater eel there.", "Ngaliny kubarr yinyay nyajil.", "ngaliny kubarr yinyay nyajil | 1du.INCL.NOM freshwater.eel there see.NONPAST", "r297_1du_incl_there_water_fauna_see_kubarr", ["ngaliny", "kubarr", "yinyay", "nyajil"]),
    row(18, "You and I see the mudcrab there.", "Ngaliny kiju yinyay nyajil.", "ngaliny kiju yinyay nyajil | 1du.INCL.NOM mudcrab there see.NONPAST", "r297_1du_incl_there_water_fauna_see_kiju", ["ngaliny", "kiju", "yinyay", "nyajil"]),
    row(19, "You and I see the prawn there.", "Ngaliny wakal yinyay nyajil.", "ngaliny wakal yinyay nyajil | 1du.INCL.NOM prawn there see.NONPAST", "r297_1du_incl_there_water_fauna_see_wakal", ["ngaliny", "wakal", "yinyay", "nyajil"]),
    row(20, "You and I see the oyster there.", "Ngaliny julul yinyay nyajil.", "ngaliny julul yinyay nyajil | 1du.INCL.NOM oyster there see.NONPAST", "r297_1du_incl_there_water_fauna_see_julul", ["ngaliny", "julul", "yinyay", "nyajil"]),
    row(21, "You two see the sea turtle here.", "Yubal ngawiya yaluy nyajil.", "yubal ngawiya yaluy nyajil | 2du.NOM sea.turtle here see.NONPAST", "r297_2du_here_water_fauna_see_ngawiya", ["yubal", "ngawiya", "yaluy", "nyajil"]),
    row(22, "You two see the freshwater turtle here.", "Yubal ngujay yaluy nyajil.", "yubal ngujay yaluy nyajil | 2du.NOM freshwater.turtle here see.NONPAST", "r297_2du_here_water_fauna_see_ngujay", ["yubal", "ngujay", "yaluy", "nyajil"]),
    row(23, "You two see the fish here.", "Yubal kuyu yaluy nyajil.", "yubal kuyu yaluy nyajil | 2du.NOM fish here see.NONPAST", "r297_2du_here_water_fauna_see_kuyu", ["yubal", "kuyu", "yaluy", "nyajil"]),
    row(24, "You two see the stingray here.", "Yubal yawu yaluy nyajil.", "yubal yawu yaluy nyajil | 2du.NOM stingray here see.NONPAST", "r297_2du_here_water_fauna_see_yawu", ["yubal", "yawu", "yaluy", "nyajil"]),
    row(25, "You two see the barramundi here.", "Yubal judi yaluy nyajil.", "yubal judi yaluy nyajil | 2du.NOM barramundi here see.NONPAST", "r297_2du_here_water_fauna_see_judi", ["yubal", "judi", "yaluy", "nyajil"]),
    row(26, "You two see the mullet here.", "Yubal ngalkun yaluy nyajil.", "yubal ngalkun yaluy nyajil | 2du.NOM mullet here see.NONPAST", "r297_2du_here_water_fauna_see_ngalkun", ["yubal", "ngalkun", "yaluy", "nyajil"]),
    row(27, "You two see the freshwater eel here.", "Yubal kubarr yaluy nyajil.", "yubal kubarr yaluy nyajil | 2du.NOM freshwater.eel here see.NONPAST", "r297_2du_here_water_fauna_see_kubarr", ["yubal", "kubarr", "yaluy", "nyajil"]),
    row(28, "You two see the mudcrab here.", "Yubal kiju yaluy nyajil.", "yubal kiju yaluy nyajil | 2du.NOM mudcrab here see.NONPAST", "r297_2du_here_water_fauna_see_kiju", ["yubal", "kiju", "yaluy", "nyajil"]),
    row(29, "You two see the prawn here.", "Yubal wakal yaluy nyajil.", "yubal wakal yaluy nyajil | 2du.NOM prawn here see.NONPAST", "r297_2du_here_water_fauna_see_wakal", ["yubal", "wakal", "yaluy", "nyajil"]),
    row(30, "You two see the oyster here.", "Yubal julul yaluy nyajil.", "yubal julul yaluy nyajil | 2du.NOM oyster here see.NONPAST", "r297_2du_here_water_fauna_see_julul", ["yubal", "julul", "yaluy", "nyajil"]),
    row(31, "You all see the sea turtle there.", "Yurra ngawiya yinyay nyajil.", "yurra ngawiya yinyay nyajil | 2pl.NOM sea.turtle there see.NONPAST", "r297_2pl_there_water_fauna_see_ngawiya", ["yurra", "ngawiya", "yinyay", "nyajil"]),
    row(32, "You all see the freshwater turtle there.", "Yurra ngujay yinyay nyajil.", "yurra ngujay yinyay nyajil | 2pl.NOM freshwater.turtle there see.NONPAST", "r297_2pl_there_water_fauna_see_ngujay", ["yurra", "ngujay", "yinyay", "nyajil"]),
    row(33, "You all see the fish there.", "Yurra kuyu yinyay nyajil.", "yurra kuyu yinyay nyajil | 2pl.NOM fish there see.NONPAST", "r297_2pl_there_water_fauna_see_kuyu", ["yurra", "kuyu", "yinyay", "nyajil"]),
    row(34, "You all see the stingray there.", "Yurra yawu yinyay nyajil.", "yurra yawu yinyay nyajil | 2pl.NOM stingray there see.NONPAST", "r297_2pl_there_water_fauna_see_yawu", ["yurra", "yawu", "yinyay", "nyajil"]),
    row(35, "You all see the barramundi there.", "Yurra judi yinyay nyajil.", "yurra judi yinyay nyajil | 2pl.NOM barramundi there see.NONPAST", "r297_2pl_there_water_fauna_see_judi", ["yurra", "judi", "yinyay", "nyajil"]),
    row(36, "You all see the mullet there.", "Yurra ngalkun yinyay nyajil.", "yurra ngalkun yinyay nyajil | 2pl.NOM mullet there see.NONPAST", "r297_2pl_there_water_fauna_see_ngalkun", ["yurra", "ngalkun", "yinyay", "nyajil"]),
    row(37, "You all see the freshwater eel there.", "Yurra kubarr yinyay nyajil.", "yurra kubarr yinyay nyajil | 2pl.NOM freshwater.eel there see.NONPAST", "r297_2pl_there_water_fauna_see_kubarr", ["yurra", "kubarr", "yinyay", "nyajil"]),
    row(38, "You all see the mudcrab there.", "Yurra kiju yinyay nyajil.", "yurra kiju yinyay nyajil | 2pl.NOM mudcrab there see.NONPAST", "r297_2pl_there_water_fauna_see_kiju", ["yurra", "kiju", "yinyay", "nyajil"]),
    row(39, "You all see the prawn there.", "Yurra wakal yinyay nyajil.", "yurra wakal yinyay nyajil | 2pl.NOM prawn there see.NONPAST", "r297_2pl_there_water_fauna_see_wakal", ["yurra", "wakal", "yinyay", "nyajil"]),
    row(40, "You all see the oyster there.", "Yurra julul yinyay nyajil.", "yurra julul yinyay nyajil | 2pl.NOM oyster there see.NONPAST", "r297_2pl_there_water_fauna_see_julul", ["yurra", "julul", "yinyay", "nyajil"]),
    row(41, "We see the sea turtle here.", "Ngana ngawiya yaluy nyajil.", "ngana ngawiya yaluy nyajil | 1pl.INCL.NOM sea.turtle here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_ngawiya", ["ngana", "ngawiya", "yaluy", "nyajil"]),
    row(42, "We see the freshwater turtle here.", "Ngana ngujay yaluy nyajil.", "ngana ngujay yaluy nyajil | 1pl.INCL.NOM freshwater.turtle here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_ngujay", ["ngana", "ngujay", "yaluy", "nyajil"]),
    row(43, "We see the fish here.", "Ngana kuyu yaluy nyajil.", "ngana kuyu yaluy nyajil | 1pl.INCL.NOM fish here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_kuyu", ["ngana", "kuyu", "yaluy", "nyajil"]),
    row(44, "We see the stingray here.", "Ngana yawu yaluy nyajil.", "ngana yawu yaluy nyajil | 1pl.INCL.NOM stingray here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_yawu", ["ngana", "yawu", "yaluy", "nyajil"]),
    row(45, "We see the barramundi here.", "Ngana judi yaluy nyajil.", "ngana judi yaluy nyajil | 1pl.INCL.NOM barramundi here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_judi", ["ngana", "judi", "yaluy", "nyajil"]),
    row(46, "We see the mullet here.", "Ngana ngalkun yaluy nyajil.", "ngana ngalkun yaluy nyajil | 1pl.INCL.NOM mullet here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_ngalkun", ["ngana", "ngalkun", "yaluy", "nyajil"]),
    row(47, "We see the freshwater eel here.", "Ngana kubarr yaluy nyajil.", "ngana kubarr yaluy nyajil | 1pl.INCL.NOM freshwater.eel here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_kubarr", ["ngana", "kubarr", "yaluy", "nyajil"]),
    row(48, "We see the mudcrab here.", "Ngana kiju yaluy nyajil.", "ngana kiju yaluy nyajil | 1pl.INCL.NOM mudcrab here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_kiju", ["ngana", "kiju", "yaluy", "nyajil"]),
    row(49, "We see the prawn here.", "Ngana wakal yaluy nyajil.", "ngana wakal yaluy nyajil | 1pl.INCL.NOM prawn here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_wakal", ["ngana", "wakal", "yaluy", "nyajil"]),
    row(50, "We see the oyster here.", "Ngana julul yaluy nyajil.", "ngana julul yaluy nyajil | 1pl.INCL.NOM oyster here see.NONPAST", "r297_1pl_incl_here_water_fauna_see_julul", ["ngana", "julul", "yaluy", "nyajil"]),
]


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 "nyajil" not in words or not lower_kuku.endswith(" nyajil."):
            issues.append(f"{seq}: missing final nyajil")
        if "nyajin" in lower_kuku:
            issues.append(f"{seq}: past nyajin 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] != "nyajil":
            issues.append(f"{seq}: word 4 is not nyajil {words[3]}")
        if lower_kuku.rstrip(".") != " ".join(words):
            issues.append(f"{seq}: Kuku does not match words_used {words}")
        if not frame.startswith("r297_"):
            issues.append(f"{seq}: frame not r297 {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", "nyajil"])
    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 NONPAST PERCEPTION SWEEP AFTER RULE 296 (Rule 297). "
        "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 nyajil. "
        "Only bare visible object nonpast 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, past/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 297 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-l nonpast support before authoring Rule 297.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="nonsingular-nonpast-scope", actor="claude-main", detail="Selected a sourced non-singular nonpast counterpart to Rules 295-296's visible water-fauna singular/third-person perception bands. The batch uses ngali, ngaliny, yubal, yurra, and ngana 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 297 visible water-fauna non-singular nonpast surfaces returned no accepted, revised, or under-review collisions over the Rule 295-296 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 nyajil, no loans, no denied Kuku forms, and no catch/spear/cook/eat/ecology/case/compound drift.", command="python3 -m py_compile batch_scripts/bank_339.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_339; print(bank_339.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_339.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 297 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_339.py", output_excerpt=f"banked batch-339: 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-339: 50 rows under_review")
    return 0


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