#!/usr/bin/env python3
"""Bank batch-333: Rule 291 low-count weapon/tool pronoun coverage."""

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-333"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-333-low-count-traditional-weapon-tool-pronoun-nonpast-perception-after-rule290-process.md"

TARGET_EVIDENCE = {
    "kurrajan": "Dictionary lines 16196-16207 give kurrajan as noun 'spear point', with source prose about wattle, fire-hardening, and turtle spearing. Rule 291 selects visible spear-point reference only.",
    "nambarr": "Dictionary lines 21516-21526 give nambarr as noun 'bamboo stick', a flexible bamboo stick used in nose piercing. Rule 291 selects visible bamboo-stick reference only.",
    "manbir": "Dictionary lines 17699-17707 give manbir as noun 'barb of a spear'. Rule 291 selects visible spear-barb reference only.",
    "wakay": "Dictionary lines 25192-25202 give wakay as noun 'wooden sword'. Rule 291 selects visible wooden-sword reference only.",
    "wulburr": "Dictionary lines 27767-27776 give wulburr as noun 'bamboo spear stick' and 'spear'. Rule 291 selects visible bamboo-spear-stick reference only.",
}

SUPPORT_EVIDENCE = (
    "Patz lines 2577-2603 source the bare nominative pronouns used here: ngayu, yundu, nyulu, ngali, "
    "ngaliny, yubal, bula, nganjin, ngana, and yurra; lines 2674-2686 source the non-singular person/number "
    "contrasts, including ngali exclusive dual, ngana inclusive plural, yubal, yurra, bula, and jana history; "
    "lines 2838-2845 source yaluy/yinyay; lines 3043-3049 source nyaji-l 'see'; and lines 3149-3151 source the "
    "nonpast function. Rule 291 uses corpus-conventional nyajil as the nonpast visual-perception surface."
)

TARGET_ORDER = ["kurrajan", "nambarr", "manbir", "wakay", "wulburr"]
FRAME_SPECS = [
    ("ngayu", "yinyay"),
    ("yundu", "yaluy"),
    ("nyulu", "yinyay"),
    ("ngali", "yaluy"),
    ("ngaliny", "yinyay"),
    ("yubal", "yaluy"),
    ("bula", "yaluy"),
    ("nganjin", "yinyay"),
    ("ngana", "yaluy"),
    ("yurra", "yinyay"),
]

DENY_KUKU = {
    "biyul", "durray", "jinil", "mirru", "kurajan", "ngurmu", "birungubay", "biruwybay", "birubay",
    "kurrajanji", "nambarriji", "manbirji", "wakayji", "wulburrji",
    "nganya", "yununy", "nyunguny", "ngalingan", "ngalinyan", "yubalan", "bulangan",
    "nganjinan", "nganangan", "yurrangan", "janangan", "ngalinka", "ngalinyanka", "yubalanka",
    "bulanka", "nganjinanka", "ngananka", "yurranka", "ngalinda", "ngalinyanda", "yubalanda",
    "bulanda", "nganjinanda", "ngananda", "yurranda", "ngalinji", "ngalinyanji", "yubalanji",
    "bulanji", "nganjinanji", "ngananji", "yurranji", "ngalinga", "ngalinyanga", "yubalanga",
    "bulanga", "nganjinanga", "ngananga", "yurranga",
    "nyajin", "nyaji-ny", "nyajiny", "nyaji-nka", "nyaji-l-nyaji", "yinyangka", "yinyayngka",
    "yinyamba", "yinyamuny", "yalungku", "yaluyngku", "yaluymbu", "yaluyundu", "yalamuny",
}
DENY_ENGLISH = (
    "cook", "cooking", "earth oven", "voya", "vine", "gather", "turtle spearing", "turtle", "wattle",
    "fire", "fire-hardening", "hardened", "pierce", "piercing", "throw", "throwing", "threw", "hunting",
    "hunt", "fighting with", "fight with", "defend", "defence", "cutting", "cut with", "stab", "stabbing",
    "injury", "nose piercing", "made", "make", "used", "use", "owned", "belongs", "route", "travel",
    "place", "story",
)


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 see the spear point there.", "Ngayu kurrajan yinyay nyajil.", "ngayu kurrajan yinyay nyajil | 1sg.NOM spear.point there see.NPST", "r291_1sg_there_low_weapon_tool_see_kurrajan", ["ngayu", "kurrajan", "yinyay", "nyajil"]),
    row(2, "I see the bamboo stick there.", "Ngayu nambarr yinyay nyajil.", "ngayu nambarr yinyay nyajil | 1sg.NOM bamboo.stick there see.NPST", "r291_1sg_there_low_weapon_tool_see_nambarr", ["ngayu", "nambarr", "yinyay", "nyajil"]),
    row(3, "I see the spear barb there.", "Ngayu manbir yinyay nyajil.", "ngayu manbir yinyay nyajil | 1sg.NOM spear.barb there see.NPST", "r291_1sg_there_low_weapon_tool_see_manbir", ["ngayu", "manbir", "yinyay", "nyajil"]),
    row(4, "I see the wooden sword there.", "Ngayu wakay yinyay nyajil.", "ngayu wakay yinyay nyajil | 1sg.NOM wooden.sword there see.NPST", "r291_1sg_there_low_weapon_tool_see_wakay", ["ngayu", "wakay", "yinyay", "nyajil"]),
    row(5, "I see the bamboo spear stick there.", "Ngayu wulburr yinyay nyajil.", "ngayu wulburr yinyay nyajil | 1sg.NOM bamboo.spear.stick there see.NPST", "r291_1sg_there_low_weapon_tool_see_wulburr", ["ngayu", "wulburr", "yinyay", "nyajil"]),
    row(6, "You see the spear point here.", "Yundu kurrajan yaluy nyajil.", "yundu kurrajan yaluy nyajil | 2sg.NOM spear.point here see.NPST", "r291_2sg_here_low_weapon_tool_see_kurrajan", ["yundu", "kurrajan", "yaluy", "nyajil"]),
    row(7, "You see the bamboo stick here.", "Yundu nambarr yaluy nyajil.", "yundu nambarr yaluy nyajil | 2sg.NOM bamboo.stick here see.NPST", "r291_2sg_here_low_weapon_tool_see_nambarr", ["yundu", "nambarr", "yaluy", "nyajil"]),
    row(8, "You see the spear barb here.", "Yundu manbir yaluy nyajil.", "yundu manbir yaluy nyajil | 2sg.NOM spear.barb here see.NPST", "r291_2sg_here_low_weapon_tool_see_manbir", ["yundu", "manbir", "yaluy", "nyajil"]),
    row(9, "You see the wooden sword here.", "Yundu wakay yaluy nyajil.", "yundu wakay yaluy nyajil | 2sg.NOM wooden.sword here see.NPST", "r291_2sg_here_low_weapon_tool_see_wakay", ["yundu", "wakay", "yaluy", "nyajil"]),
    row(10, "You see the bamboo spear stick here.", "Yundu wulburr yaluy nyajil.", "yundu wulburr yaluy nyajil | 2sg.NOM bamboo.spear.stick here see.NPST", "r291_2sg_here_low_weapon_tool_see_wulburr", ["yundu", "wulburr", "yaluy", "nyajil"]),
    row(11, "He sees the spear point there.", "Nyulu kurrajan yinyay nyajil.", "nyulu kurrajan yinyay nyajil | 3sg.NOM spear.point there see.NPST", "r291_3sg_there_low_weapon_tool_see_kurrajan", ["nyulu", "kurrajan", "yinyay", "nyajil"]),
    row(12, "He sees the bamboo stick there.", "Nyulu nambarr yinyay nyajil.", "nyulu nambarr yinyay nyajil | 3sg.NOM bamboo.stick there see.NPST", "r291_3sg_there_low_weapon_tool_see_nambarr", ["nyulu", "nambarr", "yinyay", "nyajil"]),
    row(13, "He sees the spear barb there.", "Nyulu manbir yinyay nyajil.", "nyulu manbir yinyay nyajil | 3sg.NOM spear.barb there see.NPST", "r291_3sg_there_low_weapon_tool_see_manbir", ["nyulu", "manbir", "yinyay", "nyajil"]),
    row(14, "He sees the wooden sword there.", "Nyulu wakay yinyay nyajil.", "nyulu wakay yinyay nyajil | 3sg.NOM wooden.sword there see.NPST", "r291_3sg_there_low_weapon_tool_see_wakay", ["nyulu", "wakay", "yinyay", "nyajil"]),
    row(15, "He sees the bamboo spear stick there.", "Nyulu wulburr yinyay nyajil.", "nyulu wulburr yinyay nyajil | 3sg.NOM bamboo.spear.stick there see.NPST", "r291_3sg_there_low_weapon_tool_see_wulburr", ["nyulu", "wulburr", "yinyay", "nyajil"]),
    row(16, "We two (not you) see the spear point here.", "Ngali kurrajan yaluy nyajil.", "ngali kurrajan yaluy nyajil | 1du.excl.NOM spear.point here see.NPST", "r291_1du_excl_here_low_weapon_tool_see_kurrajan", ["ngali", "kurrajan", "yaluy", "nyajil"]),
    row(17, "We two (not you) see the bamboo stick here.", "Ngali nambarr yaluy nyajil.", "ngali nambarr yaluy nyajil | 1du.excl.NOM bamboo.stick here see.NPST", "r291_1du_excl_here_low_weapon_tool_see_nambarr", ["ngali", "nambarr", "yaluy", "nyajil"]),
    row(18, "We two (not you) see the spear barb here.", "Ngali manbir yaluy nyajil.", "ngali manbir yaluy nyajil | 1du.excl.NOM spear.barb here see.NPST", "r291_1du_excl_here_low_weapon_tool_see_manbir", ["ngali", "manbir", "yaluy", "nyajil"]),
    row(19, "We two (not you) see the wooden sword here.", "Ngali wakay yaluy nyajil.", "ngali wakay yaluy nyajil | 1du.excl.NOM wooden.sword here see.NPST", "r291_1du_excl_here_low_weapon_tool_see_wakay", ["ngali", "wakay", "yaluy", "nyajil"]),
    row(20, "We two (not you) see the bamboo spear stick here.", "Ngali wulburr yaluy nyajil.", "ngali wulburr yaluy nyajil | 1du.excl.NOM bamboo.spear.stick here see.NPST", "r291_1du_excl_here_low_weapon_tool_see_wulburr", ["ngali", "wulburr", "yaluy", "nyajil"]),
    row(21, "You and I see the spear point there.", "Ngaliny kurrajan yinyay nyajil.", "ngaliny kurrajan yinyay nyajil | 1du.incl.NOM spear.point there see.NPST", "r291_1du_incl_there_low_weapon_tool_see_kurrajan", ["ngaliny", "kurrajan", "yinyay", "nyajil"]),
    row(22, "You and I see the bamboo stick there.", "Ngaliny nambarr yinyay nyajil.", "ngaliny nambarr yinyay nyajil | 1du.incl.NOM bamboo.stick there see.NPST", "r291_1du_incl_there_low_weapon_tool_see_nambarr", ["ngaliny", "nambarr", "yinyay", "nyajil"]),
    row(23, "You and I see the spear barb there.", "Ngaliny manbir yinyay nyajil.", "ngaliny manbir yinyay nyajil | 1du.incl.NOM spear.barb there see.NPST", "r291_1du_incl_there_low_weapon_tool_see_manbir", ["ngaliny", "manbir", "yinyay", "nyajil"]),
    row(24, "You and I see the wooden sword there.", "Ngaliny wakay yinyay nyajil.", "ngaliny wakay yinyay nyajil | 1du.incl.NOM wooden.sword there see.NPST", "r291_1du_incl_there_low_weapon_tool_see_wakay", ["ngaliny", "wakay", "yinyay", "nyajil"]),
    row(25, "You and I see the bamboo spear stick there.", "Ngaliny wulburr yinyay nyajil.", "ngaliny wulburr yinyay nyajil | 1du.incl.NOM bamboo.spear.stick there see.NPST", "r291_1du_incl_there_low_weapon_tool_see_wulburr", ["ngaliny", "wulburr", "yinyay", "nyajil"]),
    row(26, "You two see the spear point here.", "Yubal kurrajan yaluy nyajil.", "yubal kurrajan yaluy nyajil | 2du.NOM spear.point here see.NPST", "r291_2du_here_low_weapon_tool_see_kurrajan", ["yubal", "kurrajan", "yaluy", "nyajil"]),
    row(27, "You two see the bamboo stick here.", "Yubal nambarr yaluy nyajil.", "yubal nambarr yaluy nyajil | 2du.NOM bamboo.stick here see.NPST", "r291_2du_here_low_weapon_tool_see_nambarr", ["yubal", "nambarr", "yaluy", "nyajil"]),
    row(28, "You two see the spear barb here.", "Yubal manbir yaluy nyajil.", "yubal manbir yaluy nyajil | 2du.NOM spear.barb here see.NPST", "r291_2du_here_low_weapon_tool_see_manbir", ["yubal", "manbir", "yaluy", "nyajil"]),
    row(29, "You two see the wooden sword here.", "Yubal wakay yaluy nyajil.", "yubal wakay yaluy nyajil | 2du.NOM wooden.sword here see.NPST", "r291_2du_here_low_weapon_tool_see_wakay", ["yubal", "wakay", "yaluy", "nyajil"]),
    row(30, "You two see the bamboo spear stick here.", "Yubal wulburr yaluy nyajil.", "yubal wulburr yaluy nyajil | 2du.NOM bamboo.spear.stick here see.NPST", "r291_2du_here_low_weapon_tool_see_wulburr", ["yubal", "wulburr", "yaluy", "nyajil"]),
    row(31, "They two see the spear point here.", "Bula kurrajan yaluy nyajil.", "bula kurrajan yaluy nyajil | 3du.NOM spear.point here see.NPST", "r291_3du_here_low_weapon_tool_see_kurrajan", ["bula", "kurrajan", "yaluy", "nyajil"]),
    row(32, "They two see the bamboo stick here.", "Bula nambarr yaluy nyajil.", "bula nambarr yaluy nyajil | 3du.NOM bamboo.stick here see.NPST", "r291_3du_here_low_weapon_tool_see_nambarr", ["bula", "nambarr", "yaluy", "nyajil"]),
    row(33, "They two see the spear barb here.", "Bula manbir yaluy nyajil.", "bula manbir yaluy nyajil | 3du.NOM spear.barb here see.NPST", "r291_3du_here_low_weapon_tool_see_manbir", ["bula", "manbir", "yaluy", "nyajil"]),
    row(34, "They two see the wooden sword here.", "Bula wakay yaluy nyajil.", "bula wakay yaluy nyajil | 3du.NOM wooden.sword here see.NPST", "r291_3du_here_low_weapon_tool_see_wakay", ["bula", "wakay", "yaluy", "nyajil"]),
    row(35, "They two see the bamboo spear stick here.", "Bula wulburr yaluy nyajil.", "bula wulburr yaluy nyajil | 3du.NOM bamboo.spear.stick here see.NPST", "r291_3du_here_low_weapon_tool_see_wulburr", ["bula", "wulburr", "yaluy", "nyajil"]),
    row(36, "We all, not you, see the spear point there.", "Nganjin kurrajan yinyay nyajil.", "nganjin kurrajan yinyay nyajil | 1pl.excl.NOM spear.point there see.NPST", "r291_1pl_excl_there_low_weapon_tool_see_kurrajan", ["nganjin", "kurrajan", "yinyay", "nyajil"]),
    row(37, "We all, not you, see the bamboo stick there.", "Nganjin nambarr yinyay nyajil.", "nganjin nambarr yinyay nyajil | 1pl.excl.NOM bamboo.stick there see.NPST", "r291_1pl_excl_there_low_weapon_tool_see_nambarr", ["nganjin", "nambarr", "yinyay", "nyajil"]),
    row(38, "We all, not you, see the spear barb there.", "Nganjin manbir yinyay nyajil.", "nganjin manbir yinyay nyajil | 1pl.excl.NOM spear.barb there see.NPST", "r291_1pl_excl_there_low_weapon_tool_see_manbir", ["nganjin", "manbir", "yinyay", "nyajil"]),
    row(39, "We all, not you, see the wooden sword there.", "Nganjin wakay yinyay nyajil.", "nganjin wakay yinyay nyajil | 1pl.excl.NOM wooden.sword there see.NPST", "r291_1pl_excl_there_low_weapon_tool_see_wakay", ["nganjin", "wakay", "yinyay", "nyajil"]),
    row(40, "We all, not you, see the bamboo spear stick there.", "Nganjin wulburr yinyay nyajil.", "nganjin wulburr yinyay nyajil | 1pl.excl.NOM bamboo.spear.stick there see.NPST", "r291_1pl_excl_there_low_weapon_tool_see_wulburr", ["nganjin", "wulburr", "yinyay", "nyajil"]),
    row(41, "We see the spear point here.", "Ngana kurrajan yaluy nyajil.", "ngana kurrajan yaluy nyajil | 1pl.incl.NOM spear.point here see.NPST", "r291_1pl_incl_here_low_weapon_tool_see_kurrajan", ["ngana", "kurrajan", "yaluy", "nyajil"]),
    row(42, "We see the bamboo stick here.", "Ngana nambarr yaluy nyajil.", "ngana nambarr yaluy nyajil | 1pl.incl.NOM bamboo.stick here see.NPST", "r291_1pl_incl_here_low_weapon_tool_see_nambarr", ["ngana", "nambarr", "yaluy", "nyajil"]),
    row(43, "We see the spear barb here.", "Ngana manbir yaluy nyajil.", "ngana manbir yaluy nyajil | 1pl.incl.NOM spear.barb here see.NPST", "r291_1pl_incl_here_low_weapon_tool_see_manbir", ["ngana", "manbir", "yaluy", "nyajil"]),
    row(44, "We see the wooden sword here.", "Ngana wakay yaluy nyajil.", "ngana wakay yaluy nyajil | 1pl.incl.NOM wooden.sword here see.NPST", "r291_1pl_incl_here_low_weapon_tool_see_wakay", ["ngana", "wakay", "yaluy", "nyajil"]),
    row(45, "We see the bamboo spear stick here.", "Ngana wulburr yaluy nyajil.", "ngana wulburr yaluy nyajil | 1pl.incl.NOM bamboo.spear.stick here see.NPST", "r291_1pl_incl_here_low_weapon_tool_see_wulburr", ["ngana", "wulburr", "yaluy", "nyajil"]),
    row(46, "You all see the spear point there.", "Yurra kurrajan yinyay nyajil.", "yurra kurrajan yinyay nyajil | 2pl.NOM spear.point there see.NPST", "r291_2pl_there_low_weapon_tool_see_kurrajan", ["yurra", "kurrajan", "yinyay", "nyajil"]),
    row(47, "You all see the bamboo stick there.", "Yurra nambarr yinyay nyajil.", "yurra nambarr yinyay nyajil | 2pl.NOM bamboo.stick there see.NPST", "r291_2pl_there_low_weapon_tool_see_nambarr", ["yurra", "nambarr", "yinyay", "nyajil"]),
    row(48, "You all see the spear barb there.", "Yurra manbir yinyay nyajil.", "yurra manbir yinyay nyajil | 2pl.NOM spear.barb there see.NPST", "r291_2pl_there_low_weapon_tool_see_manbir", ["yurra", "manbir", "yinyay", "nyajil"]),
    row(49, "You all see the wooden sword there.", "Yurra wakay yinyay nyajil.", "yurra wakay yinyay nyajil | 2pl.NOM wooden.sword there see.NPST", "r291_2pl_there_low_weapon_tool_see_wakay", ["yurra", "wakay", "yinyay", "nyajil"]),
    row(50, "You all see the bamboo spear stick there.", "Yurra wulburr yinyay nyajil.", "yurra wulburr yinyay nyajil | 2pl.NOM bamboo.spear.stick there see.NPST", "r291_2pl_there_low_weapon_tool_see_wulburr", ["yurra", "wulburr", "yinyay", "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 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) // 5]
        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) % 5]:
            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("r291_"):
            issues.append(f"{seq}: frame not r291 {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", "ngali", "ngaliny", "yubal", "bula", "nganjin", "ngana", "yurra", "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 = (
        "LOW-COUNT VISIBLE TRADITIONAL WEAPON/TOOL TEN-PRONOUN NONPAST PERCEPTION SWEEP AFTER RULE 290 "
        "(Rule 291). 50 under-review rows over five lower-count checked targets: kurrajan spear point, nambarr "
        "bamboo stick, manbir spear barb, wakay wooden sword, and wulburr bamboo spear stick. SUPPORT: bare "
        "nominative ngayu, yundu, nyulu, ngali, ngaliny, yubal, bula, nganjin, ngana, and yurra, plus yaluy/yinyay "
        "and nyajil. Only bare visible object nonpast perception/reference rows are opened; weapon use, cooking, "
        "earth-oven/vine source, turtle spearing, fire-hardening, nose-piercing, throwing, hunting, fighting, "
        "piercing, cutting, material-source, 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 291 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 dictionary source lines for five lower-count visible traditional weapon/tool targets and Patz pronoun, demonstrative, and nyaji-l nonpast support before authoring Rule 291.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="pronoun-coverage-scope", actor="claude-main", detail="Selected a ten-pronoun nonpast perception coverage consolidation over the five lowest-count Rule 289/290 weapon/tool targets. The batch alternates local demonstratives to avoid prior singular/third surfaces and does not open weapon-use 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 291 low-count weapon/tool ten-pronoun nonpast surfaces returned no accepted, revised, or under-review collisions.", 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 pronoun bands, bare yaluy/yinyay, final nyajil, no loans, no denied Kuku forms, and no weapon-use/source-prose/case/compound drift.", command="python3 -m py_compile batch_scripts/bank_333.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_333; print(bank_333.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_333.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 291 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_333.py", output_excerpt=f"banked batch-333: 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-333: 50 rows under_review")
    return 0


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