#!/usr/bin/env python3
"""Bank batch-341: Rule 299 insect 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-341"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-341-insect-nonsingular-past-perception-after-rule298-process.md"

TARGET_EVIDENCE = {
    "balarr": "Dictionary line readback in Rules 255/256/270/271 gives balarr as 'flea'. Rule 299 selects visible flea reference only and leaves body, bite, sickness, pest-control, and event rows closed.",
    "dijaraban": "Dictionary line readback in Rules 255/256/270/271 gives dijaraban as 'mayfly'. Rule 299 selects visible mayfly reference only and leaves dragonfly expansion and ecology rows closed.",
    "kalburiji": "Dictionary line readback in Rules 255/256/270/271 gives kalburiji as a kalburiji bee. Rule 299 selects visible bee-label reference only and leaves honey, nest, egg, larvae, collecting, edible, and source-prose rows closed.",
    "mawal": "Dictionary line readback in Rules 255/256/270/271 gives mawal as a mawal bee. Rule 299 selects visible bee-label reference only and leaves honey, nest, egg, larvae, collecting, edible, and source-prose rows closed.",
    "munudumbun": "Dictionary line readback in Rules 255/256/270/271 gives munudumbun as 'scorpion'. Rule 299 selects visible scorpion reference only and leaves sting, poison, danger, sickness, and event rows closed.",
    "munyurri": "Dictionary line readback in Rules 255/256/270/271 gives munyurri as 'sandfly'. Rule 299 selects visible sandfly reference only and leaves biting, sickness, pest-control, and event rows closed.",
    "nakawarra": "Dictionary line readback in Rules 255/256/270/271 gives nakawarra as a nakawarra bee. Rule 299 selects visible bee-label reference only and leaves honey, nest, collecting, edible, and source-prose rows closed.",
    "ngalmnbu": "Dictionary line readback in Rules 255/256/270/271 gives ngalmnbu as 'jumper ant'. Rule 299 selects visible ant-label reference only and leaves jumping, bite, sting, antbed, and event rows closed.",
    "yarrka": "Dictionary line readback in Rules 255/256/270/271 gives yarrka as a yarrka bee. Rule 299 selects visible bee-label reference only and leaves smallest, bush, honey, nest, collecting, and source-prose rows closed.",
    "yiljun": "Dictionary line readback in Rules 255/256/270/271 gives yiljun as 'grasshopper'. Rule 299 selects visible grasshopper reference only and leaves singing, yam-readiness, seasonal-signal, movement, and event 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 299 uses corpus-conventional nyajin as the past visual-perception surface."
)

TARGET_ORDER = ["balarr", "dijaraban", "kalburiji", "mawal", "munudumbun", "munyurri", "nakawarra", "ngalmnbu", "yarrka", "yiljun"]
FRAME_SPECS = [
    ("ngali", "yaluy"),
    ("ngaliny", "yinyay"),
    ("yubal", "yaluy"),
    ("yurra", "yinyay"),
    ("ngana", "yaluy"),
]

DENY_KUKU = {
    "munukurru", "diri-diri", "dabu", "wunba", "kuja", "yangka", "nyirran", "karrkil", "murma",
    "wurrbu", "dabadaba", "dujandujan", "kalkamal", "kuran", "kurrmaja", "nyumbil", "malal",
    "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",
    "nganjin", "nganjinan", "nganjinanka", "nganjinanda", "nganjinandamuny", "nganjinanji",
    "nganya", "yununy", "nyunguny", "bulangan", "janangan", "yalungku", "yaluyngku",
    "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajil", "nyaji-l", "nyaji-nka", "nyaji-l-nyaji", "milka", "baykal", "jalngkay",
}
DENY_ENGLISH = (
    "bite", "biting", "bitten", "sting", "stinging", "poison", "danger", "dangerous", "sick", "sickness",
    "vomit", "larvae", "larva", "egg", "eggs", "honey", "nest", "collect", "collecting", "edible", "food",
    "medicine", "season", "seasonal", "sing", "singing", "jump", "jumping", "antbed", "pest", "body",
    "human", "tree", "wood", "habitat", "ecology", "movement", "event", "yam", "readiness", "smallest",
    "bush", "dragonfly",
)


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 flea here.", "Ngali balarr yaluy nyajin.", "ngali balarr yaluy nyajin | 1du.EXCL.NOM flea here see.PAST", "r299_1du_excl_here_insect_saw_balarr", ["ngali", "balarr", "yaluy", "nyajin"]),
    row(2, "We two, not you, saw the mayfly here.", "Ngali dijaraban yaluy nyajin.", "ngali dijaraban yaluy nyajin | 1du.EXCL.NOM mayfly here see.PAST", "r299_1du_excl_here_insect_saw_dijaraban", ["ngali", "dijaraban", "yaluy", "nyajin"]),
    row(3, "We two, not you, saw the kalburiji bee here.", "Ngali kalburiji yaluy nyajin.", "ngali kalburiji yaluy nyajin | 1du.EXCL.NOM kalburiji.bee here see.PAST", "r299_1du_excl_here_insect_saw_kalburiji", ["ngali", "kalburiji", "yaluy", "nyajin"]),
    row(4, "We two, not you, saw the mawal bee here.", "Ngali mawal yaluy nyajin.", "ngali mawal yaluy nyajin | 1du.EXCL.NOM mawal.bee here see.PAST", "r299_1du_excl_here_insect_saw_mawal", ["ngali", "mawal", "yaluy", "nyajin"]),
    row(5, "We two, not you, saw the scorpion here.", "Ngali munudumbun yaluy nyajin.", "ngali munudumbun yaluy nyajin | 1du.EXCL.NOM scorpion here see.PAST", "r299_1du_excl_here_insect_saw_munudumbun", ["ngali", "munudumbun", "yaluy", "nyajin"]),
    row(6, "We two, not you, saw the sandfly here.", "Ngali munyurri yaluy nyajin.", "ngali munyurri yaluy nyajin | 1du.EXCL.NOM sandfly here see.PAST", "r299_1du_excl_here_insect_saw_munyurri", ["ngali", "munyurri", "yaluy", "nyajin"]),
    row(7, "We two, not you, saw the nakawarra bee here.", "Ngali nakawarra yaluy nyajin.", "ngali nakawarra yaluy nyajin | 1du.EXCL.NOM nakawarra.bee here see.PAST", "r299_1du_excl_here_insect_saw_nakawarra", ["ngali", "nakawarra", "yaluy", "nyajin"]),
    row(8, "We two, not you, saw the jumper ant here.", "Ngali ngalmnbu yaluy nyajin.", "ngali ngalmnbu yaluy nyajin | 1du.EXCL.NOM jumper.ant here see.PAST", "r299_1du_excl_here_insect_saw_ngalmnbu", ["ngali", "ngalmnbu", "yaluy", "nyajin"]),
    row(9, "We two, not you, saw the yarrka bee here.", "Ngali yarrka yaluy nyajin.", "ngali yarrka yaluy nyajin | 1du.EXCL.NOM yarrka.bee here see.PAST", "r299_1du_excl_here_insect_saw_yarrka", ["ngali", "yarrka", "yaluy", "nyajin"]),
    row(10, "We two, not you, saw the grasshopper here.", "Ngali yiljun yaluy nyajin.", "ngali yiljun yaluy nyajin | 1du.EXCL.NOM grasshopper here see.PAST", "r299_1du_excl_here_insect_saw_yiljun", ["ngali", "yiljun", "yaluy", "nyajin"]),
    row(11, "You and I saw the flea there.", "Ngaliny balarr yinyay nyajin.", "ngaliny balarr yinyay nyajin | 1du.INCL.NOM flea there see.PAST", "r299_1du_incl_there_insect_saw_balarr", ["ngaliny", "balarr", "yinyay", "nyajin"]),
    row(12, "You and I saw the mayfly there.", "Ngaliny dijaraban yinyay nyajin.", "ngaliny dijaraban yinyay nyajin | 1du.INCL.NOM mayfly there see.PAST", "r299_1du_incl_there_insect_saw_dijaraban", ["ngaliny", "dijaraban", "yinyay", "nyajin"]),
    row(13, "You and I saw the kalburiji bee there.", "Ngaliny kalburiji yinyay nyajin.", "ngaliny kalburiji yinyay nyajin | 1du.INCL.NOM kalburiji.bee there see.PAST", "r299_1du_incl_there_insect_saw_kalburiji", ["ngaliny", "kalburiji", "yinyay", "nyajin"]),
    row(14, "You and I saw the mawal bee there.", "Ngaliny mawal yinyay nyajin.", "ngaliny mawal yinyay nyajin | 1du.INCL.NOM mawal.bee there see.PAST", "r299_1du_incl_there_insect_saw_mawal", ["ngaliny", "mawal", "yinyay", "nyajin"]),
    row(15, "You and I saw the scorpion there.", "Ngaliny munudumbun yinyay nyajin.", "ngaliny munudumbun yinyay nyajin | 1du.INCL.NOM scorpion there see.PAST", "r299_1du_incl_there_insect_saw_munudumbun", ["ngaliny", "munudumbun", "yinyay", "nyajin"]),
    row(16, "You and I saw the sandfly there.", "Ngaliny munyurri yinyay nyajin.", "ngaliny munyurri yinyay nyajin | 1du.INCL.NOM sandfly there see.PAST", "r299_1du_incl_there_insect_saw_munyurri", ["ngaliny", "munyurri", "yinyay", "nyajin"]),
    row(17, "You and I saw the nakawarra bee there.", "Ngaliny nakawarra yinyay nyajin.", "ngaliny nakawarra yinyay nyajin | 1du.INCL.NOM nakawarra.bee there see.PAST", "r299_1du_incl_there_insect_saw_nakawarra", ["ngaliny", "nakawarra", "yinyay", "nyajin"]),
    row(18, "You and I saw the jumper ant there.", "Ngaliny ngalmnbu yinyay nyajin.", "ngaliny ngalmnbu yinyay nyajin | 1du.INCL.NOM jumper.ant there see.PAST", "r299_1du_incl_there_insect_saw_ngalmnbu", ["ngaliny", "ngalmnbu", "yinyay", "nyajin"]),
    row(19, "You and I saw the yarrka bee there.", "Ngaliny yarrka yinyay nyajin.", "ngaliny yarrka yinyay nyajin | 1du.INCL.NOM yarrka.bee there see.PAST", "r299_1du_incl_there_insect_saw_yarrka", ["ngaliny", "yarrka", "yinyay", "nyajin"]),
    row(20, "You and I saw the grasshopper there.", "Ngaliny yiljun yinyay nyajin.", "ngaliny yiljun yinyay nyajin | 1du.INCL.NOM grasshopper there see.PAST", "r299_1du_incl_there_insect_saw_yiljun", ["ngaliny", "yiljun", "yinyay", "nyajin"]),
    row(21, "You two saw the flea here.", "Yubal balarr yaluy nyajin.", "yubal balarr yaluy nyajin | 2du.NOM flea here see.PAST", "r299_2du_here_insect_saw_balarr", ["yubal", "balarr", "yaluy", "nyajin"]),
    row(22, "You two saw the mayfly here.", "Yubal dijaraban yaluy nyajin.", "yubal dijaraban yaluy nyajin | 2du.NOM mayfly here see.PAST", "r299_2du_here_insect_saw_dijaraban", ["yubal", "dijaraban", "yaluy", "nyajin"]),
    row(23, "You two saw the kalburiji bee here.", "Yubal kalburiji yaluy nyajin.", "yubal kalburiji yaluy nyajin | 2du.NOM kalburiji.bee here see.PAST", "r299_2du_here_insect_saw_kalburiji", ["yubal", "kalburiji", "yaluy", "nyajin"]),
    row(24, "You two saw the mawal bee here.", "Yubal mawal yaluy nyajin.", "yubal mawal yaluy nyajin | 2du.NOM mawal.bee here see.PAST", "r299_2du_here_insect_saw_mawal", ["yubal", "mawal", "yaluy", "nyajin"]),
    row(25, "You two saw the scorpion here.", "Yubal munudumbun yaluy nyajin.", "yubal munudumbun yaluy nyajin | 2du.NOM scorpion here see.PAST", "r299_2du_here_insect_saw_munudumbun", ["yubal", "munudumbun", "yaluy", "nyajin"]),
    row(26, "You two saw the sandfly here.", "Yubal munyurri yaluy nyajin.", "yubal munyurri yaluy nyajin | 2du.NOM sandfly here see.PAST", "r299_2du_here_insect_saw_munyurri", ["yubal", "munyurri", "yaluy", "nyajin"]),
    row(27, "You two saw the nakawarra bee here.", "Yubal nakawarra yaluy nyajin.", "yubal nakawarra yaluy nyajin | 2du.NOM nakawarra.bee here see.PAST", "r299_2du_here_insect_saw_nakawarra", ["yubal", "nakawarra", "yaluy", "nyajin"]),
    row(28, "You two saw the jumper ant here.", "Yubal ngalmnbu yaluy nyajin.", "yubal ngalmnbu yaluy nyajin | 2du.NOM jumper.ant here see.PAST", "r299_2du_here_insect_saw_ngalmnbu", ["yubal", "ngalmnbu", "yaluy", "nyajin"]),
    row(29, "You two saw the yarrka bee here.", "Yubal yarrka yaluy nyajin.", "yubal yarrka yaluy nyajin | 2du.NOM yarrka.bee here see.PAST", "r299_2du_here_insect_saw_yarrka", ["yubal", "yarrka", "yaluy", "nyajin"]),
    row(30, "You two saw the grasshopper here.", "Yubal yiljun yaluy nyajin.", "yubal yiljun yaluy nyajin | 2du.NOM grasshopper here see.PAST", "r299_2du_here_insect_saw_yiljun", ["yubal", "yiljun", "yaluy", "nyajin"]),
    row(31, "You all saw the flea there.", "Yurra balarr yinyay nyajin.", "yurra balarr yinyay nyajin | 2pl.NOM flea there see.PAST", "r299_2pl_there_insect_saw_balarr", ["yurra", "balarr", "yinyay", "nyajin"]),
    row(32, "You all saw the mayfly there.", "Yurra dijaraban yinyay nyajin.", "yurra dijaraban yinyay nyajin | 2pl.NOM mayfly there see.PAST", "r299_2pl_there_insect_saw_dijaraban", ["yurra", "dijaraban", "yinyay", "nyajin"]),
    row(33, "You all saw the kalburiji bee there.", "Yurra kalburiji yinyay nyajin.", "yurra kalburiji yinyay nyajin | 2pl.NOM kalburiji.bee there see.PAST", "r299_2pl_there_insect_saw_kalburiji", ["yurra", "kalburiji", "yinyay", "nyajin"]),
    row(34, "You all saw the mawal bee there.", "Yurra mawal yinyay nyajin.", "yurra mawal yinyay nyajin | 2pl.NOM mawal.bee there see.PAST", "r299_2pl_there_insect_saw_mawal", ["yurra", "mawal", "yinyay", "nyajin"]),
    row(35, "You all saw the scorpion there.", "Yurra munudumbun yinyay nyajin.", "yurra munudumbun yinyay nyajin | 2pl.NOM scorpion there see.PAST", "r299_2pl_there_insect_saw_munudumbun", ["yurra", "munudumbun", "yinyay", "nyajin"]),
    row(36, "You all saw the sandfly there.", "Yurra munyurri yinyay nyajin.", "yurra munyurri yinyay nyajin | 2pl.NOM sandfly there see.PAST", "r299_2pl_there_insect_saw_munyurri", ["yurra", "munyurri", "yinyay", "nyajin"]),
    row(37, "You all saw the nakawarra bee there.", "Yurra nakawarra yinyay nyajin.", "yurra nakawarra yinyay nyajin | 2pl.NOM nakawarra.bee there see.PAST", "r299_2pl_there_insect_saw_nakawarra", ["yurra", "nakawarra", "yinyay", "nyajin"]),
    row(38, "You all saw the jumper ant there.", "Yurra ngalmnbu yinyay nyajin.", "yurra ngalmnbu yinyay nyajin | 2pl.NOM jumper.ant there see.PAST", "r299_2pl_there_insect_saw_ngalmnbu", ["yurra", "ngalmnbu", "yinyay", "nyajin"]),
    row(39, "You all saw the yarrka bee there.", "Yurra yarrka yinyay nyajin.", "yurra yarrka yinyay nyajin | 2pl.NOM yarrka.bee there see.PAST", "r299_2pl_there_insect_saw_yarrka", ["yurra", "yarrka", "yinyay", "nyajin"]),
    row(40, "You all saw the grasshopper there.", "Yurra yiljun yinyay nyajin.", "yurra yiljun yinyay nyajin | 2pl.NOM grasshopper there see.PAST", "r299_2pl_there_insect_saw_yiljun", ["yurra", "yiljun", "yinyay", "nyajin"]),
    row(41, "We saw the flea here.", "Ngana balarr yaluy nyajin.", "ngana balarr yaluy nyajin | 1pl.INCL.NOM flea here see.PAST", "r299_1pl_incl_here_insect_saw_balarr", ["ngana", "balarr", "yaluy", "nyajin"]),
    row(42, "We saw the mayfly here.", "Ngana dijaraban yaluy nyajin.", "ngana dijaraban yaluy nyajin | 1pl.INCL.NOM mayfly here see.PAST", "r299_1pl_incl_here_insect_saw_dijaraban", ["ngana", "dijaraban", "yaluy", "nyajin"]),
    row(43, "We saw the kalburiji bee here.", "Ngana kalburiji yaluy nyajin.", "ngana kalburiji yaluy nyajin | 1pl.INCL.NOM kalburiji.bee here see.PAST", "r299_1pl_incl_here_insect_saw_kalburiji", ["ngana", "kalburiji", "yaluy", "nyajin"]),
    row(44, "We saw the mawal bee here.", "Ngana mawal yaluy nyajin.", "ngana mawal yaluy nyajin | 1pl.INCL.NOM mawal.bee here see.PAST", "r299_1pl_incl_here_insect_saw_mawal", ["ngana", "mawal", "yaluy", "nyajin"]),
    row(45, "We saw the scorpion here.", "Ngana munudumbun yaluy nyajin.", "ngana munudumbun yaluy nyajin | 1pl.INCL.NOM scorpion here see.PAST", "r299_1pl_incl_here_insect_saw_munudumbun", ["ngana", "munudumbun", "yaluy", "nyajin"]),
    row(46, "We saw the sandfly here.", "Ngana munyurri yaluy nyajin.", "ngana munyurri yaluy nyajin | 1pl.INCL.NOM sandfly here see.PAST", "r299_1pl_incl_here_insect_saw_munyurri", ["ngana", "munyurri", "yaluy", "nyajin"]),
    row(47, "We saw the nakawarra bee here.", "Ngana nakawarra yaluy nyajin.", "ngana nakawarra yaluy nyajin | 1pl.INCL.NOM nakawarra.bee here see.PAST", "r299_1pl_incl_here_insect_saw_nakawarra", ["ngana", "nakawarra", "yaluy", "nyajin"]),
    row(48, "We saw the jumper ant here.", "Ngana ngalmnbu yaluy nyajin.", "ngana ngalmnbu yaluy nyajin | 1pl.INCL.NOM jumper.ant here see.PAST", "r299_1pl_incl_here_insect_saw_ngalmnbu", ["ngana", "ngalmnbu", "yaluy", "nyajin"]),
    row(49, "We saw the yarrka bee here.", "Ngana yarrka yaluy nyajin.", "ngana yarrka yaluy nyajin | 1pl.INCL.NOM yarrka.bee here see.PAST", "r299_1pl_incl_here_insect_saw_yarrka", ["ngana", "yarrka", "yaluy", "nyajin"]),
    row(50, "We saw the grasshopper here.", "Ngana yiljun yaluy nyajin.", "ngana yiljun yaluy nyajin | 1pl.INCL.NOM grasshopper here see.PAST", "r299_1pl_incl_here_insect_saw_yiljun", ["ngana", "yiljun", "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("r299_"):
            issues.append(f"{seq}: frame not r299 {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 = (
        "INSECT NON-SINGULAR PAST PERCEPTION SWEEP AFTER RULE 298 (Rule 299). "
        "50 under-review rows over ten checked insect target heads: balarr flea, dijaraban mayfly, kalburiji bee, "
        "mawal bee, munudumbun scorpion, munyurri sandfly, nakawarra bee, ngalmnbu jumper ant, yarrka bee, and "
        "yiljun grasshopper. SUPPORT: bare nominative ngali, ngaliny, yubal, yurra, and ngana, plus yaluy/yinyay "
        "and nyajin. Only bare visible object past perception/reference rows are opened; biting, stinging, poison, "
        "sickness, honey, nest, eggs, larvae, collecting, edible/food/medicine, seasonal-signal, singing, jumping, "
        "antbed, body/human-body, ecology, danger, event, 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 299 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 recorded dictionary line readbacks for ten Rule 255/256/270/271 insect targets and Patz pronoun, demonstrative, and nyaji-ny past support before authoring Rule 299.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="insect-nonsingular-past-scope", actor="claude-main", detail="Selected a sourced non-singular past counterpart to earlier insect non-singular nonpast perception bands. The batch uses ngali, ngaliny, yubal, yurra, and ngana with nyajin, and does not open biting, stinging, honey, nest, larvae, medicine, 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 299 insect non-singular past surfaces returned no accepted, revised, or under-review collisions over the Rule 255/256/270/271 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 bite/sting/honey/nest/larvae/medicine/ecology/case/compound drift.", command="python3 -m py_compile batch_scripts/bank_341.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_341; print(bank_341.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_341.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 299 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_341.py", output_excerpt=f"banked batch-341: 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-341: 50 rows under_review")
    return 0


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