#!/usr/bin/env python3
"""Bank batch-335: Rule 293 complementary weapon/tool 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-335"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-335-traditional-weapon-tool-complementary-nonsingular-nonpast-perception-after-rule292-process.md"

TARGET_EVIDENCE = {
    "bangkal": "Dictionary lines 1478-1489 give bangkal as noun 'tongs', made from voya vine and used with kurrma. Rule 293 selects visible tongs reference only and leaves cooking/vine/earth-oven/action rows closed.",
    "kurrajan": "Dictionary lines 16196-16207 give kurrajan as noun 'spear point', with source prose about wattle, fire-hardening, and turtle spearing. Rule 293 selects visible spear-point reference only.",
    "dara": "Dictionary lines 5215-5226 give dara as noun 'bamboo spear stick'. Rule 293 selects visible spear-stick reference only.",
    "jaba": "Dictionary lines 6843-6857 give jaba as noun 'stick', also sapling, post, walking stick, and horn. Rule 293 selects visible stick reference only.",
    "kunjuri": "Dictionary lines 15915-15923 give kunjuri as noun 'shield'. Rule 293 selects visible shield reference only.",
    "nambarr": "Dictionary lines 21516-21526 give nambarr as noun 'bamboo stick', a flexible bamboo stick used in nose piercing. Rule 293 selects visible bamboo-stick reference only.",
    "wangal": "Dictionary lines 25943-25951 give wangal as noun 'boomerang'. Rule 293 selects visible boomerang reference only.",
    "manbir": "Dictionary lines 17699-17707 give manbir as noun 'barb of a spear'. Rule 293 selects visible spear-barb reference only.",
    "wakay": "Dictionary lines 25192-25202 give wakay as noun 'wooden sword'. Rule 293 selects visible wooden-sword reference only.",
    "wulburr": "Dictionary lines 27767-27776 give wulburr as noun 'bamboo spear stick' and 'spear'. Rule 293 selects visible bamboo-spear-stick reference only.",
}

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

TARGET_ORDER = ["bangkal", "kurrajan", "dara", "jaba", "kunjuri", "nambarr", "wangal", "manbir", "wakay", "wulburr"]
FRAME_SPECS = [
    ("ngali", "yinyay"),
    ("ngaliny", "yaluy"),
    ("yubal", "yinyay"),
    ("nganjin", "yaluy"),
    ("ngana", "yinyay"),
]

DENY_KUKU = {
    "biyul", "durray", "jinil", "mirru", "kurajan", "ngurmu", "birungubay", "biruwybay", "birubay",
    "bangkalji", "kurrajanji", "daraji", "jabaji", "kunjuriji", "nambarriji", "wangalji",
    "manbirji", "wakayji", "wulburrji", "ngalingan", "ngalinyan", "yubalan", "nganjinan",
    "nganangan", "ngalinka", "ngalinyanka", "yubalanka", "nganjinanka", "ngananka", "ngalinda",
    "ngalinyanda", "yubalanda", "nganjinanda", "ngananda", "ngalinji", "ngalinyanji", "yubalanji",
    "nganjinanji", "ngananji", "ngalinga", "ngalinyanga", "yubalanga", "nganjinanga", "ngananga",
    "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, "We two (not you) see the tongs there.", "Ngali bangkal yinyay nyajil.", "ngali bangkal yinyay nyajil | 1du.excl.NOM tongs there see.NPST", "r293_1du_excl_there_weapon_tool_see_bangkal", ["ngali", "bangkal", "yinyay", "nyajil"]),
    row(2, "We two (not you) see the spear point there.", "Ngali kurrajan yinyay nyajil.", "ngali kurrajan yinyay nyajil | 1du.excl.NOM spear.point there see.NPST", "r293_1du_excl_there_weapon_tool_see_kurrajan", ["ngali", "kurrajan", "yinyay", "nyajil"]),
    row(3, "We two (not you) see the bamboo spear stick there.", "Ngali dara yinyay nyajil.", "ngali dara yinyay nyajil | 1du.excl.NOM bamboo.spear.stick there see.NPST", "r293_1du_excl_there_weapon_tool_see_dara", ["ngali", "dara", "yinyay", "nyajil"]),
    row(4, "We two (not you) see the stick there.", "Ngali jaba yinyay nyajil.", "ngali jaba yinyay nyajil | 1du.excl.NOM stick there see.NPST", "r293_1du_excl_there_weapon_tool_see_jaba", ["ngali", "jaba", "yinyay", "nyajil"]),
    row(5, "We two (not you) see the shield there.", "Ngali kunjuri yinyay nyajil.", "ngali kunjuri yinyay nyajil | 1du.excl.NOM shield there see.NPST", "r293_1du_excl_there_weapon_tool_see_kunjuri", ["ngali", "kunjuri", "yinyay", "nyajil"]),
    row(6, "We two (not you) see the bamboo stick there.", "Ngali nambarr yinyay nyajil.", "ngali nambarr yinyay nyajil | 1du.excl.NOM bamboo.stick there see.NPST", "r293_1du_excl_there_weapon_tool_see_nambarr", ["ngali", "nambarr", "yinyay", "nyajil"]),
    row(7, "We two (not you) see the boomerang there.", "Ngali wangal yinyay nyajil.", "ngali wangal yinyay nyajil | 1du.excl.NOM boomerang there see.NPST", "r293_1du_excl_there_weapon_tool_see_wangal", ["ngali", "wangal", "yinyay", "nyajil"]),
    row(8, "We two (not you) see the spear barb there.", "Ngali manbir yinyay nyajil.", "ngali manbir yinyay nyajil | 1du.excl.NOM spear.barb there see.NPST", "r293_1du_excl_there_weapon_tool_see_manbir", ["ngali", "manbir", "yinyay", "nyajil"]),
    row(9, "We two (not you) see the wooden sword there.", "Ngali wakay yinyay nyajil.", "ngali wakay yinyay nyajil | 1du.excl.NOM wooden.sword there see.NPST", "r293_1du_excl_there_weapon_tool_see_wakay", ["ngali", "wakay", "yinyay", "nyajil"]),
    row(10, "We two (not you) see the bamboo spear stick there.", "Ngali wulburr yinyay nyajil.", "ngali wulburr yinyay nyajil | 1du.excl.NOM bamboo.spear.stick there see.NPST", "r293_1du_excl_there_weapon_tool_see_wulburr", ["ngali", "wulburr", "yinyay", "nyajil"]),
    row(11, "You and I see the tongs here.", "Ngaliny bangkal yaluy nyajil.", "ngaliny bangkal yaluy nyajil | 1du.incl.NOM tongs here see.NPST", "r293_1du_incl_here_weapon_tool_see_bangkal", ["ngaliny", "bangkal", "yaluy", "nyajil"]),
    row(12, "You and I see the spear point here.", "Ngaliny kurrajan yaluy nyajil.", "ngaliny kurrajan yaluy nyajil | 1du.incl.NOM spear.point here see.NPST", "r293_1du_incl_here_weapon_tool_see_kurrajan", ["ngaliny", "kurrajan", "yaluy", "nyajil"]),
    row(13, "You and I see the bamboo spear stick here.", "Ngaliny dara yaluy nyajil.", "ngaliny dara yaluy nyajil | 1du.incl.NOM bamboo.spear.stick here see.NPST", "r293_1du_incl_here_weapon_tool_see_dara", ["ngaliny", "dara", "yaluy", "nyajil"]),
    row(14, "You and I see the stick here.", "Ngaliny jaba yaluy nyajil.", "ngaliny jaba yaluy nyajil | 1du.incl.NOM stick here see.NPST", "r293_1du_incl_here_weapon_tool_see_jaba", ["ngaliny", "jaba", "yaluy", "nyajil"]),
    row(15, "You and I see the shield here.", "Ngaliny kunjuri yaluy nyajil.", "ngaliny kunjuri yaluy nyajil | 1du.incl.NOM shield here see.NPST", "r293_1du_incl_here_weapon_tool_see_kunjuri", ["ngaliny", "kunjuri", "yaluy", "nyajil"]),
    row(16, "You and I see the bamboo stick here.", "Ngaliny nambarr yaluy nyajil.", "ngaliny nambarr yaluy nyajil | 1du.incl.NOM bamboo.stick here see.NPST", "r293_1du_incl_here_weapon_tool_see_nambarr", ["ngaliny", "nambarr", "yaluy", "nyajil"]),
    row(17, "You and I see the boomerang here.", "Ngaliny wangal yaluy nyajil.", "ngaliny wangal yaluy nyajil | 1du.incl.NOM boomerang here see.NPST", "r293_1du_incl_here_weapon_tool_see_wangal", ["ngaliny", "wangal", "yaluy", "nyajil"]),
    row(18, "You and I see the spear barb here.", "Ngaliny manbir yaluy nyajil.", "ngaliny manbir yaluy nyajil | 1du.incl.NOM spear.barb here see.NPST", "r293_1du_incl_here_weapon_tool_see_manbir", ["ngaliny", "manbir", "yaluy", "nyajil"]),
    row(19, "You and I see the wooden sword here.", "Ngaliny wakay yaluy nyajil.", "ngaliny wakay yaluy nyajil | 1du.incl.NOM wooden.sword here see.NPST", "r293_1du_incl_here_weapon_tool_see_wakay", ["ngaliny", "wakay", "yaluy", "nyajil"]),
    row(20, "You and I see the bamboo spear stick here.", "Ngaliny wulburr yaluy nyajil.", "ngaliny wulburr yaluy nyajil | 1du.incl.NOM bamboo.spear.stick here see.NPST", "r293_1du_incl_here_weapon_tool_see_wulburr", ["ngaliny", "wulburr", "yaluy", "nyajil"]),
    row(21, "You two see the tongs there.", "Yubal bangkal yinyay nyajil.", "yubal bangkal yinyay nyajil | 2du.NOM tongs there see.NPST", "r293_2du_there_weapon_tool_see_bangkal", ["yubal", "bangkal", "yinyay", "nyajil"]),
    row(22, "You two see the spear point there.", "Yubal kurrajan yinyay nyajil.", "yubal kurrajan yinyay nyajil | 2du.NOM spear.point there see.NPST", "r293_2du_there_weapon_tool_see_kurrajan", ["yubal", "kurrajan", "yinyay", "nyajil"]),
    row(23, "You two see the bamboo spear stick there.", "Yubal dara yinyay nyajil.", "yubal dara yinyay nyajil | 2du.NOM bamboo.spear.stick there see.NPST", "r293_2du_there_weapon_tool_see_dara", ["yubal", "dara", "yinyay", "nyajil"]),
    row(24, "You two see the stick there.", "Yubal jaba yinyay nyajil.", "yubal jaba yinyay nyajil | 2du.NOM stick there see.NPST", "r293_2du_there_weapon_tool_see_jaba", ["yubal", "jaba", "yinyay", "nyajil"]),
    row(25, "You two see the shield there.", "Yubal kunjuri yinyay nyajil.", "yubal kunjuri yinyay nyajil | 2du.NOM shield there see.NPST", "r293_2du_there_weapon_tool_see_kunjuri", ["yubal", "kunjuri", "yinyay", "nyajil"]),
    row(26, "You two see the bamboo stick there.", "Yubal nambarr yinyay nyajil.", "yubal nambarr yinyay nyajil | 2du.NOM bamboo.stick there see.NPST", "r293_2du_there_weapon_tool_see_nambarr", ["yubal", "nambarr", "yinyay", "nyajil"]),
    row(27, "You two see the boomerang there.", "Yubal wangal yinyay nyajil.", "yubal wangal yinyay nyajil | 2du.NOM boomerang there see.NPST", "r293_2du_there_weapon_tool_see_wangal", ["yubal", "wangal", "yinyay", "nyajil"]),
    row(28, "You two see the spear barb there.", "Yubal manbir yinyay nyajil.", "yubal manbir yinyay nyajil | 2du.NOM spear.barb there see.NPST", "r293_2du_there_weapon_tool_see_manbir", ["yubal", "manbir", "yinyay", "nyajil"]),
    row(29, "You two see the wooden sword there.", "Yubal wakay yinyay nyajil.", "yubal wakay yinyay nyajil | 2du.NOM wooden.sword there see.NPST", "r293_2du_there_weapon_tool_see_wakay", ["yubal", "wakay", "yinyay", "nyajil"]),
    row(30, "You two see the bamboo spear stick there.", "Yubal wulburr yinyay nyajil.", "yubal wulburr yinyay nyajil | 2du.NOM bamboo.spear.stick there see.NPST", "r293_2du_there_weapon_tool_see_wulburr", ["yubal", "wulburr", "yinyay", "nyajil"]),
    row(31, "We all, not you, see the tongs here.", "Nganjin bangkal yaluy nyajil.", "nganjin bangkal yaluy nyajil | 1pl.excl.NOM tongs here see.NPST", "r293_1pl_excl_here_weapon_tool_see_bangkal", ["nganjin", "bangkal", "yaluy", "nyajil"]),
    row(32, "We all, not you, see the spear point here.", "Nganjin kurrajan yaluy nyajil.", "nganjin kurrajan yaluy nyajil | 1pl.excl.NOM spear.point here see.NPST", "r293_1pl_excl_here_weapon_tool_see_kurrajan", ["nganjin", "kurrajan", "yaluy", "nyajil"]),
    row(33, "We all, not you, see the bamboo spear stick here.", "Nganjin dara yaluy nyajil.", "nganjin dara yaluy nyajil | 1pl.excl.NOM bamboo.spear.stick here see.NPST", "r293_1pl_excl_here_weapon_tool_see_dara", ["nganjin", "dara", "yaluy", "nyajil"]),
    row(34, "We all, not you, see the stick here.", "Nganjin jaba yaluy nyajil.", "nganjin jaba yaluy nyajil | 1pl.excl.NOM stick here see.NPST", "r293_1pl_excl_here_weapon_tool_see_jaba", ["nganjin", "jaba", "yaluy", "nyajil"]),
    row(35, "We all, not you, see the shield here.", "Nganjin kunjuri yaluy nyajil.", "nganjin kunjuri yaluy nyajil | 1pl.excl.NOM shield here see.NPST", "r293_1pl_excl_here_weapon_tool_see_kunjuri", ["nganjin", "kunjuri", "yaluy", "nyajil"]),
    row(36, "We all, not you, see the bamboo stick here.", "Nganjin nambarr yaluy nyajil.", "nganjin nambarr yaluy nyajil | 1pl.excl.NOM bamboo.stick here see.NPST", "r293_1pl_excl_here_weapon_tool_see_nambarr", ["nganjin", "nambarr", "yaluy", "nyajil"]),
    row(37, "We all, not you, see the boomerang here.", "Nganjin wangal yaluy nyajil.", "nganjin wangal yaluy nyajil | 1pl.excl.NOM boomerang here see.NPST", "r293_1pl_excl_here_weapon_tool_see_wangal", ["nganjin", "wangal", "yaluy", "nyajil"]),
    row(38, "We all, not you, see the spear barb here.", "Nganjin manbir yaluy nyajil.", "nganjin manbir yaluy nyajil | 1pl.excl.NOM spear.barb here see.NPST", "r293_1pl_excl_here_weapon_tool_see_manbir", ["nganjin", "manbir", "yaluy", "nyajil"]),
    row(39, "We all, not you, see the wooden sword here.", "Nganjin wakay yaluy nyajil.", "nganjin wakay yaluy nyajil | 1pl.excl.NOM wooden.sword here see.NPST", "r293_1pl_excl_here_weapon_tool_see_wakay", ["nganjin", "wakay", "yaluy", "nyajil"]),
    row(40, "We all, not you, see the bamboo spear stick here.", "Nganjin wulburr yaluy nyajil.", "nganjin wulburr yaluy nyajil | 1pl.excl.NOM bamboo.spear.stick here see.NPST", "r293_1pl_excl_here_weapon_tool_see_wulburr", ["nganjin", "wulburr", "yaluy", "nyajil"]),
    row(41, "We see the tongs there.", "Ngana bangkal yinyay nyajil.", "ngana bangkal yinyay nyajil | 1pl.incl.NOM tongs there see.NPST", "r293_1pl_incl_there_weapon_tool_see_bangkal", ["ngana", "bangkal", "yinyay", "nyajil"]),
    row(42, "We see the spear point there.", "Ngana kurrajan yinyay nyajil.", "ngana kurrajan yinyay nyajil | 1pl.incl.NOM spear.point there see.NPST", "r293_1pl_incl_there_weapon_tool_see_kurrajan", ["ngana", "kurrajan", "yinyay", "nyajil"]),
    row(43, "We see the bamboo spear stick there.", "Ngana dara yinyay nyajil.", "ngana dara yinyay nyajil | 1pl.incl.NOM bamboo.spear.stick there see.NPST", "r293_1pl_incl_there_weapon_tool_see_dara", ["ngana", "dara", "yinyay", "nyajil"]),
    row(44, "We see the stick there.", "Ngana jaba yinyay nyajil.", "ngana jaba yinyay nyajil | 1pl.incl.NOM stick there see.NPST", "r293_1pl_incl_there_weapon_tool_see_jaba", ["ngana", "jaba", "yinyay", "nyajil"]),
    row(45, "We see the shield there.", "Ngana kunjuri yinyay nyajil.", "ngana kunjuri yinyay nyajil | 1pl.incl.NOM shield there see.NPST", "r293_1pl_incl_there_weapon_tool_see_kunjuri", ["ngana", "kunjuri", "yinyay", "nyajil"]),
    row(46, "We see the bamboo stick there.", "Ngana nambarr yinyay nyajil.", "ngana nambarr yinyay nyajil | 1pl.incl.NOM bamboo.stick there see.NPST", "r293_1pl_incl_there_weapon_tool_see_nambarr", ["ngana", "nambarr", "yinyay", "nyajil"]),
    row(47, "We see the boomerang there.", "Ngana wangal yinyay nyajil.", "ngana wangal yinyay nyajil | 1pl.incl.NOM boomerang there see.NPST", "r293_1pl_incl_there_weapon_tool_see_wangal", ["ngana", "wangal", "yinyay", "nyajil"]),
    row(48, "We see the spear barb there.", "Ngana manbir yinyay nyajil.", "ngana manbir yinyay nyajil | 1pl.incl.NOM spear.barb there see.NPST", "r293_1pl_incl_there_weapon_tool_see_manbir", ["ngana", "manbir", "yinyay", "nyajil"]),
    row(49, "We see the wooden sword there.", "Ngana wakay yinyay nyajil.", "ngana wakay yinyay nyajil | 1pl.incl.NOM wooden.sword there see.NPST", "r293_1pl_incl_there_weapon_tool_see_wakay", ["ngana", "wakay", "yinyay", "nyajil"]),
    row(50, "We see the bamboo spear stick there.", "Ngana wulburr yinyay nyajil.", "ngana wulburr yinyay nyajil | 1pl.incl.NOM bamboo.spear.stick there see.NPST", "r293_1pl_incl_there_weapon_tool_see_wulburr", ["ngana", "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) // 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("r293_"):
            issues.append(f"{seq}: frame not r293 {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", "nganjin", "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 TRADITIONAL WEAPON/TOOL COMPLEMENTARY NON-SINGULAR NONPAST PERCEPTION SWEEP AFTER RULE 292 "
        "(Rule 293). 50 under-review rows over ten checked targets: bangkal tongs, kurrajan spear point, dara "
        "bamboo spear stick, jaba stick, kunjuri shield, nambarr bamboo stick, wangal boomerang, manbir spear barb, "
        "wakay wooden sword, and wulburr bamboo spear stick. SUPPORT: bare nominative ngali, ngaliny, yubal, "
        "nganjin, and ngana, plus yaluy/yinyay and nyajil. Only bare visible object nonpast perception/reference "
        "rows are opened; weapon use, cooking, 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 293 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 ten visible traditional weapon/tool targets and Patz non-singular pronoun, demonstrative, and nyaji-l nonpast support before authoring Rule 293.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="complementary-pronoun-scope", actor="claude-main", detail="Selected complementary local-demonstrative non-singular nonpast perception bands over the Rule 289/290 traditional weapon/tool target set. The batch fills zero-collision ngali, ngaliny, yubal, nganjin, and ngana bands 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 293 traditional weapon/tool complementary non-singular 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 non-singular 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_335.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_335; print(bank_335.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_335.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 293 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_335.py", output_excerpt=f"banked batch-335: 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-335: 50 rows under_review")
    return 0


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