#!/usr/bin/env python3
"""Bank batch-242: Rule 200 distal-demonstrative tree-reference consolidation."""

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-242"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-242-distal-demonstrative-tree-reference-consolidation-after-rule199-process.md"

TARGET_HEADS = {
    "jinjajalka": "jinjajalka tree",
    "kurunkal": "kurunkal mangrove",
    "madu": "madu sea pine",
    "marngkil": "marngkil ti tree",
    "marrabal": "marrabal ti tree",
    "milbarakal": "milbarakal tree",
    "mungari": "mungari kaori pine",
    "wurmbariji": "wurmbariji scrub tree",
    "wuymbariji": "wuymbariji scrub tree",
    "kurrun": "kurrun tree",
}
SUPPORT = {"ngayu", "yundu", "jana", "yinya", "yinyay", "nyaji-l"}
DENY_KUKU = {
    "mayi", "nuka", "nukan", "waju", "wajun", "warrmba", "warrmban", "mani", "manin",
    "daji", "dajin", "dinda", "dindan", "duda", "dudan", "wukurri", "wukurrin",
    "ngara", "ngaran", "kuni", "kunin", "yaka", "yakan", "balka", "balkan",
    "kida", "kidan", "dunga", "dungan", "wandi", "wandin", "baya", "kubu",
    "bubu", "bayan", "bana", "jalun", "jikan", "nganka", "diburr", "wunba",
    "dukul", "wawu", "buyku", "bijan", "marril", "mirrbangku", "miyilabu",
    "ngadil", "nyumbil", "wanakan", "wankar", "yurrunji", "yala", "yanyu",
}
DENY_ENGLISH = (
    "fruit", "fruits", "seed", "seeds", "edible", "eat", "eats", "ate", "food",
    "medicine", "medicinal", "poison", "poisonous", "sap", "timber", "wood", "bark",
    "oar", "oars", "woomera", "spear", "burn", "burning", "cut", "cutting",
    "gather", "gathering", "grow", "growing", "ecology", "place", "place-name",
    "story", "country", "own", "ownership", "necklace", "leech", "bird", "jellyfish",
    "shell", "button", "wing", "zamia", "leaf", "leaves", "flower", "flowers",
    "honey", "grub", "bait", "use", "used", "make", "making", "material", "source",
)


def js(values: list[str]) -> str:
    return json.dumps(values, ensure_ascii=False)


def row(
    seq: int,
    english: str,
    kuku: str,
    analysis: str,
    frame: str,
    words: list[str],
    evidence: str,
) -> tuple:
    return (seq, english, kuku, analysis, frame, 3, js(words), js([]), evidence, "0.86")


ROWS = [
    row(1, "That jinjajalka tree is there.", "Yinya jinjajalka yinyay.", "yinya jinjajalka yinyay | that jinjajalka.tree there", "r200_preposed_yinya_present_jinjajalka", ["yinya", "jinjajalka", "yinyay"], "Patz NP order yinya + noun; dictionary jinjajalka tree only."),
    row(2, "That kurunkal mangrove is there.", "Yinya kurunkal yinyay.", "yinya kurunkal yinyay | that kurunkal.mangrove there", "r200_preposed_yinya_present_kurunkal", ["yinya", "kurunkal", "yinyay"], "Patz NP order yinya + noun; dictionary kurunkal mangrove only; seed/habitat prose closed."),
    row(3, "That madu sea pine is there.", "Yinya madu yinyay.", "yinya madu yinyay | that madu.sea.pine there", "r200_preposed_yinya_present_madu", ["yinya", "madu", "yinyay"], "Patz NP order yinya + noun; dictionary madu sea pine only."),
    row(4, "That marngkil ti tree is there.", "Yinya marngkil yinyay.", "yinya marngkil yinyay | that marngkil.ti.tree there", "r200_preposed_yinya_present_marngkil", ["yinya", "marngkil", "yinyay"], "Patz NP order yinya + noun; dictionary marngkil ti tree only; zemia/wing drift closed."),
    row(5, "That marrabal ti tree is there.", "Yinya marrabal yinyay.", "yinya marrabal yinyay | that marrabal.ti.tree there", "r200_preposed_yinya_present_marrabal", ["yinya", "marrabal", "yinyay"], "Patz NP order yinya + noun; dictionary marrabal ti tree only; shell/button drift closed."),
    row(6, "That milbarakal tree is there.", "Yinya milbarakal yinyay.", "yinya milbarakal yinyay | that milbarakal.tree there", "r200_preposed_yinya_present_milbarakal", ["yinya", "milbarakal", "yinyay"], "Patz NP order yinya + noun; dictionary milbarakal tree only."),
    row(7, "That mungari kaori pine is there.", "Yinya mungari yinyay.", "yinya mungari yinyay | that mungari.kaori.pine there", "r200_preposed_yinya_present_mungari", ["yinya", "mungari", "yinyay"], "Patz NP order yinya + noun; dictionary mungari kaori/kauri pine only."),
    row(8, "That wurmbariji scrub tree is there.", "Yinya wurmbariji yinyay.", "yinya wurmbariji yinyay | that wurmbariji.scrub.tree there", "r200_preposed_yinya_present_wurmbariji", ["yinya", "wurmbariji", "yinyay"], "Patz NP order yinya + noun; dictionary wurmbariji scrub tree only; jellyfish drift closed."),
    row(9, "That wuymbariji scrub tree is there.", "Yinya wuymbariji yinyay.", "yinya wuymbariji yinyay | that wuymbariji.scrub.tree there", "r200_preposed_yinya_present_wuymbariji", ["yinya", "wuymbariji", "yinyay"], "Patz NP order yinya + noun; dictionary wuymbariji scrub tree only."),
    row(10, "That kurrun tree is there.", "Yinya kurrun yinyay.", "yinya kurrun yinyay | that kurrun.tree there", "r200_preposed_yinya_present_kurrun", ["yinya", "kurrun", "yinyay"], "Patz NP order yinya + noun; dictionary kurrun tree only; bird homograph closed."),
    row(11, "That jinjajalka tree is there.", "Jinjajalka yinya yinyay.", "jinjajalka yinya yinyay | jinjajalka.tree that there", "r200_postposed_yinya_present_jinjajalka", ["jinjajalka", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary jinjajalka tree only."),
    row(12, "That kurunkal mangrove is there.", "Kurunkal yinya yinyay.", "kurunkal yinya yinyay | kurunkal.mangrove that there", "r200_postposed_yinya_present_kurunkal", ["kurunkal", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary kurunkal mangrove only; seed/habitat prose closed."),
    row(13, "That madu sea pine is there.", "Madu yinya yinyay.", "madu yinya yinyay | madu.sea.pine that there", "r200_postposed_yinya_present_madu", ["madu", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary madu sea pine only."),
    row(14, "That marngkil ti tree is there.", "Marngkil yinya yinyay.", "marngkil yinya yinyay | marngkil.ti.tree that there", "r200_postposed_yinya_present_marngkil", ["marngkil", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary marngkil ti tree only; zemia/wing drift closed."),
    row(15, "That marrabal ti tree is there.", "Marrabal yinya yinyay.", "marrabal yinya yinyay | marrabal.ti.tree that there", "r200_postposed_yinya_present_marrabal", ["marrabal", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary marrabal ti tree only; shell/button drift closed."),
    row(16, "That milbarakal tree is there.", "Milbarakal yinya yinyay.", "milbarakal yinya yinyay | milbarakal.tree that there", "r200_postposed_yinya_present_milbarakal", ["milbarakal", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary milbarakal tree only."),
    row(17, "That mungari kaori pine is there.", "Mungari yinya yinyay.", "mungari yinya yinyay | mungari.kaori.pine that there", "r200_postposed_yinya_present_mungari", ["mungari", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary mungari kaori/kauri pine only."),
    row(18, "That wurmbariji scrub tree is there.", "Wurmbariji yinya yinyay.", "wurmbariji yinya yinyay | wurmbariji.scrub.tree that there", "r200_postposed_yinya_present_wurmbariji", ["wurmbariji", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary wurmbariji scrub tree only; jellyfish drift closed."),
    row(19, "That wuymbariji scrub tree is there.", "Wuymbariji yinya yinyay.", "wuymbariji yinya yinyay | wuymbariji.scrub.tree that there", "r200_postposed_yinya_present_wuymbariji", ["wuymbariji", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary wuymbariji scrub tree only."),
    row(20, "That kurrun tree is there.", "Kurrun yinya yinyay.", "kurrun yinya yinyay | kurrun.tree that there", "r200_postposed_yinya_present_kurrun", ["kurrun", "yinya", "yinyay"], "Patz NP order noun + yinya; dictionary kurrun tree only; bird homograph closed."),
    row(21, "I see that jinjajalka tree.", "Ngayu yinya jinjajalka nyajil.", "ngayu yinya jinjajalka nyaji-l | I that jinjajalka.tree see-NONPAST", "r200_1sg_preposed_yinya_object_jinjajalka", ["ngayu", "yinya", "jinjajalka", "nyaji-l"], "Patz demonstrative object NP with yinya; nyaji-l visual reading only."),
    row(22, "I see that kurunkal mangrove.", "Ngayu yinya kurunkal nyajil.", "ngayu yinya kurunkal nyaji-l | I that kurunkal.mangrove see-NONPAST", "r200_1sg_preposed_yinya_object_kurunkal", ["ngayu", "yinya", "kurunkal", "nyaji-l"], "Patz demonstrative object NP with yinya; kurunkal seed/habitat prose closed."),
    row(23, "I see that madu sea pine.", "Ngayu yinya madu nyajil.", "ngayu yinya madu nyaji-l | I that madu.sea.pine see-NONPAST", "r200_1sg_preposed_yinya_object_madu", ["ngayu", "yinya", "madu", "nyaji-l"], "Patz demonstrative object NP with yinya; nyaji-l visual reading only."),
    row(24, "I see that marngkil ti tree.", "Ngayu yinya marngkil nyajil.", "ngayu yinya marngkil nyaji-l | I that marngkil.ti.tree see-NONPAST", "r200_1sg_preposed_yinya_object_marngkil", ["ngayu", "yinya", "marngkil", "nyaji-l"], "Patz demonstrative object NP with yinya; marngkil zemia/wing drift closed."),
    row(25, "I see that marrabal ti tree.", "Ngayu yinya marrabal nyajil.", "ngayu yinya marrabal nyaji-l | I that marrabal.ti.tree see-NONPAST", "r200_1sg_preposed_yinya_object_marrabal", ["ngayu", "yinya", "marrabal", "nyaji-l"], "Patz demonstrative object NP with yinya; marrabal shell/button drift closed."),
    row(26, "I see that milbarakal tree.", "Ngayu yinya milbarakal nyajil.", "ngayu yinya milbarakal nyaji-l | I that milbarakal.tree see-NONPAST", "r200_1sg_preposed_yinya_object_milbarakal", ["ngayu", "yinya", "milbarakal", "nyaji-l"], "Patz demonstrative object NP with yinya; milbarakal tree only."),
    row(27, "I see that mungari kaori pine.", "Ngayu yinya mungari nyajil.", "ngayu yinya mungari nyaji-l | I that mungari.kaori.pine see-NONPAST", "r200_1sg_preposed_yinya_object_mungari", ["ngayu", "yinya", "mungari", "nyaji-l"], "Patz demonstrative object NP with yinya; mungari kaori/kauri pine only."),
    row(28, "I see that wurmbariji scrub tree.", "Ngayu yinya wurmbariji nyajil.", "ngayu yinya wurmbariji nyaji-l | I that wurmbariji.scrub.tree see-NONPAST", "r200_1sg_preposed_yinya_object_wurmbariji", ["ngayu", "yinya", "wurmbariji", "nyaji-l"], "Patz demonstrative object NP with yinya; wurmbariji jellyfish drift closed."),
    row(29, "I see that wuymbariji scrub tree.", "Ngayu yinya wuymbariji nyajil.", "ngayu yinya wuymbariji nyaji-l | I that wuymbariji.scrub.tree see-NONPAST", "r200_1sg_preposed_yinya_object_wuymbariji", ["ngayu", "yinya", "wuymbariji", "nyaji-l"], "Patz demonstrative object NP with yinya; wuymbariji tree only."),
    row(30, "I see that kurrun tree.", "Ngayu yinya kurrun nyajil.", "ngayu yinya kurrun nyaji-l | I that kurrun.tree see-NONPAST", "r200_1sg_preposed_yinya_object_kurrun", ["ngayu", "yinya", "kurrun", "nyaji-l"], "Patz demonstrative object NP with yinya; kurrun bird homograph closed."),
    row(31, "You see that jinjajalka tree.", "Yundu jinjajalka yinya nyajil.", "yundu jinjajalka yinya nyaji-l | you jinjajalka.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_jinjajalka", ["yundu", "jinjajalka", "yinya", "nyaji-l"], "Patz noun + yinya object NP; pronoun A bare."),
    row(32, "You see that kurunkal mangrove.", "Yundu kurunkal yinya nyajil.", "yundu kurunkal yinya nyaji-l | you kurunkal.mangrove that see-NONPAST", "r200_2sg_postposed_yinya_object_kurunkal", ["yundu", "kurunkal", "yinya", "nyaji-l"], "Patz noun + yinya object NP; kurunkal seed/habitat prose closed."),
    row(33, "You see that madu sea pine.", "Yundu madu yinya nyajil.", "yundu madu yinya nyaji-l | you madu.sea.pine that see-NONPAST", "r200_2sg_postposed_yinya_object_madu", ["yundu", "madu", "yinya", "nyaji-l"], "Patz noun + yinya object NP; pronoun A bare."),
    row(34, "You see that marngkil ti tree.", "Yundu marngkil yinya nyajil.", "yundu marngkil yinya nyaji-l | you marngkil.ti.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_marngkil", ["yundu", "marngkil", "yinya", "nyaji-l"], "Patz noun + yinya object NP; marngkil zemia/wing drift closed."),
    row(35, "You see that marrabal ti tree.", "Yundu marrabal yinya nyajil.", "yundu marrabal yinya nyaji-l | you marrabal.ti.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_marrabal", ["yundu", "marrabal", "yinya", "nyaji-l"], "Patz noun + yinya object NP; marrabal shell/button drift closed."),
    row(36, "You see that milbarakal tree.", "Yundu milbarakal yinya nyajil.", "yundu milbarakal yinya nyaji-l | you milbarakal.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_milbarakal", ["yundu", "milbarakal", "yinya", "nyaji-l"], "Patz noun + yinya object NP; milbarakal tree only."),
    row(37, "You see that mungari kaori pine.", "Yundu mungari yinya nyajil.", "yundu mungari yinya nyaji-l | you mungari.kaori.pine that see-NONPAST", "r200_2sg_postposed_yinya_object_mungari", ["yundu", "mungari", "yinya", "nyaji-l"], "Patz noun + yinya object NP; mungari kaori/kauri pine only."),
    row(38, "You see that wurmbariji scrub tree.", "Yundu wurmbariji yinya nyajil.", "yundu wurmbariji yinya nyaji-l | you wurmbariji.scrub.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_wurmbariji", ["yundu", "wurmbariji", "yinya", "nyaji-l"], "Patz noun + yinya object NP; wurmbariji jellyfish drift closed."),
    row(39, "You see that wuymbariji scrub tree.", "Yundu wuymbariji yinya nyajil.", "yundu wuymbariji yinya nyaji-l | you wuymbariji.scrub.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_wuymbariji", ["yundu", "wuymbariji", "yinya", "nyaji-l"], "Patz noun + yinya object NP; wuymbariji tree only."),
    row(40, "You see that kurrun tree.", "Yundu kurrun yinya nyajil.", "yundu kurrun yinya nyaji-l | you kurrun.tree that see-NONPAST", "r200_2sg_postposed_yinya_object_kurrun", ["yundu", "kurrun", "yinya", "nyaji-l"], "Patz noun + yinya object NP; kurrun bird homograph closed."),
    row(41, "They saw that jinjajalka tree.", "Jana yinya jinjajalka nyajin.", "jana yinya jinjajalka nyaji-ny | they that jinjajalka.tree see-PAST", "r200_3pl_preposed_yinya_past_object_jinjajalka", ["jana", "yinya", "jinjajalka", "nyaji-l"], "Patz demonstrative object NP with yinya; past nyajin surface."),
    row(42, "They saw that kurunkal mangrove.", "Jana yinya kurunkal nyajin.", "jana yinya kurunkal nyaji-ny | they that kurunkal.mangrove see-PAST", "r200_3pl_preposed_yinya_past_object_kurunkal", ["jana", "yinya", "kurunkal", "nyaji-l"], "Patz demonstrative object NP with yinya; kurunkal seed/habitat prose closed."),
    row(43, "They saw that madu sea pine.", "Jana yinya madu nyajin.", "jana yinya madu nyaji-ny | they that madu.sea.pine see-PAST", "r200_3pl_preposed_yinya_past_object_madu", ["jana", "yinya", "madu", "nyaji-l"], "Patz demonstrative object NP with yinya; past nyajin surface."),
    row(44, "They saw that marngkil ti tree.", "Jana yinya marngkil nyajin.", "jana yinya marngkil nyaji-ny | they that marngkil.ti.tree see-PAST", "r200_3pl_preposed_yinya_past_object_marngkil", ["jana", "yinya", "marngkil", "nyaji-l"], "Patz demonstrative object NP with yinya; marngkil zemia/wing drift closed."),
    row(45, "They saw that marrabal ti tree.", "Jana yinya marrabal nyajin.", "jana yinya marrabal nyaji-ny | they that marrabal.ti.tree see-PAST", "r200_3pl_preposed_yinya_past_object_marrabal", ["jana", "yinya", "marrabal", "nyaji-l"], "Patz demonstrative object NP with yinya; marrabal shell/button drift closed."),
    row(46, "They saw that milbarakal tree.", "Jana yinya milbarakal nyajin.", "jana yinya milbarakal nyaji-ny | they that milbarakal.tree see-PAST", "r200_3pl_preposed_yinya_past_object_milbarakal", ["jana", "yinya", "milbarakal", "nyaji-l"], "Patz demonstrative object NP with yinya; milbarakal tree only."),
    row(47, "They saw that mungari kaori pine.", "Jana yinya mungari nyajin.", "jana yinya mungari nyaji-ny | they that mungari.kaori.pine see-PAST", "r200_3pl_preposed_yinya_past_object_mungari", ["jana", "yinya", "mungari", "nyaji-l"], "Patz demonstrative object NP with yinya; mungari kaori/kauri pine only."),
    row(48, "They saw that wurmbariji scrub tree.", "Jana yinya wurmbariji nyajin.", "jana yinya wurmbariji nyaji-ny | they that wurmbariji.scrub.tree see-PAST", "r200_3pl_preposed_yinya_past_object_wurmbariji", ["jana", "yinya", "wurmbariji", "nyaji-l"], "Patz demonstrative object NP with yinya; wurmbariji jellyfish drift closed."),
    row(49, "They saw that wuymbariji scrub tree.", "Jana yinya wuymbariji nyajin.", "jana yinya wuymbariji nyaji-ny | they that wuymbariji.scrub.tree see-PAST", "r200_3pl_preposed_yinya_past_object_wuymbariji", ["jana", "yinya", "wuymbariji", "nyaji-l"], "Patz demonstrative object NP with yinya; wuymbariji tree only."),
    row(50, "They saw that kurrun tree.", "Jana yinya kurrun nyajin.", "jana yinya kurrun nyaji-ny | they that kurrun.tree see-PAST", "r200_3pl_preposed_yinya_past_object_kurrun", ["jana", "yinya", "kurrun", "nyaji-l"], "Patz demonstrative object NP with yinya; kurrun bird homograph closed."),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", low) is not None


def has_target_morphology(low: str, head: str) -> bool:
    suffixes = "ngka|ngku|angka|nga|ngu|ba|mba|mbu|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu|iji|nda|ndu|anda|undu|unji|nji|kari|baka|baja|bungal|bungan|mal|man|rriny"
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:{suffixes})\b", low) is not None


def english_has_denied(english_low: str, denied: str) -> bool:
    return denied in english_low if " " in denied else re.search(rf"\b{re.escape(denied)}\b", english_low) is not None


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"{LABEL}: expected 50 rows, found {len(ROWS)}")
    seen_ku: set[str] = set()
    for expected, row_data in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row_data
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        if seq != expected:
            issues.append(f"{label}: sequence mismatch; expected {expected}")
        if not english[:1].isupper() or english[-1:] not in ".!?":
            issues.append(f"{label}: English punctuation/capitalization failure")
        if " | " not in analysis:
            issues.append(f"{label}: analysis missing gloss separator")
        if not frame.startswith("r200_"):
            issues.append(f"{label}: Rule 200 frame must start with r200_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        if json.loads(loans_used):
            issues.append(f"{label}: no loans are admitted in Rule 200")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied use/homograph/proximal token {denied!r}")
        targets = [head for head in TARGET_HEADS if has_token(low, head)]
        if len(targets) != 1:
            issues.append(f"{label}: expected exactly one Rule 199 tree target, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected.replace(" ", ".") not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected.replace(' ', '.')}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        for support in SUPPORT:
            if support == "nyaji-l":
                continue
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if not has_token(low, "yinya"):
            issues.append(f"{label}: Rule 200 requires distal demonstrative yinya")
        if 1 <= seq <= 10 and (not low.startswith("yinya ") or not low.endswith(" yinyay.") or "nyaji-l" in words):
            issues.append(f"{label}: rows 1-10 require Yinya TARGET yinyay")
        if 11 <= seq <= 20 and (not low.endswith(" yinya yinyay.") or low.startswith("yinya ") or "nyaji-l" in words):
            issues.append(f"{label}: rows 11-20 require TARGET yinya yinyay")
        if 21 <= seq <= 30 and (not low.startswith("ngayu yinya ") or not low.endswith(" nyajil.") or "nyaji-l" not in words):
            issues.append(f"{label}: rows 21-30 require Ngayu yinya TARGET nyajil")
        if 31 <= seq <= 40 and (not low.startswith("yundu ") or not low.endswith(" yinya nyajil.") or "nyaji-l" not in words):
            issues.append(f"{label}: rows 31-40 require Yundu TARGET yinya nyajil")
        if 41 <= seq <= 50 and (not low.startswith("jana yinya ") or not low.endswith(" nyajin.") or "nyaji-l" not in words):
            issues.append(f"{label}: rows 41-50 require Jana yinya TARGET nyajin")
        if "nyajin" in low and "see-PAST" not in analysis:
            issues.append(f"{label}: nyajin must be glossed as see-PAST")
        if "nyajil" in low and "see-NONPAST" not in analysis:
            issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied tree-use/source-prose field in English")
        if not evidence or not confidence:
            issues.append(f"{label}: missing evidence/confidence")
    return issues


def main() -> int:
    issues = scan_static()
    if issues:
        print("pre-bank scan failed:")
        for issue in issues:
            print(f"  - {issue}")
        return 1

    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    existing = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()
    if existing:
        batch_id = existing[0]
        accepted = db.execute(
            "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status IN ('accepted','revised')",
            (batch_id,),
        ).fetchone()[0]
        if accepted:
            raise SystemExit(f"{LABEL} already has accepted/revised rows; refusing to overwrite")
        db.execute("DELETE FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)", (batch_id,))
        db.execute("DELETE FROM sentences WHERE batch_id=?", (batch_id,))
        db.execute("UPDATE batches SET notes=?, created_at=? WHERE id=?", ("rebanked under_review", NOW, batch_id))
    else:
        cur = db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (
                LABEL,
                "Rule 200 draft: distal-demonstrative tree-reference consolidation after Rule 199",
                "operator-guide-2026-07-08",
                "under_review",
                NOW,
            ),
        )
        batch_id = cur.lastrowid

    dupes: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        hit = db.execute(
            """
            SELECT b.label, s.seq
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(trim(s.kuku))=lower(trim(?))
              AND s.status!='rejected'
              AND s.batch_id!=?
            """,
            (kuku, batch_id),
        ).fetchone()
        if hit:
            dupes.append(f"{LABEL}.{seq:02d} duplicates {hit[0]}.{hit[1]:02d}: {kuku}")
    if dupes:
        db.rollback()
        print("cross-corpus duplicate check failed:")
        for dupe in dupes:
            print(f"  - {dupe}")
        return 1

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail="Rule 200 source pass selected distal demonstrative NP consolidation for the ten Rule 199 tree heads. Patz grammar 3.7 gives yinya 'that/those' and yinyay 'there'; grammar 4.1 gives yinya karrkay / karrkay yinya as preposed/postposed demonstrative NP order; grammar 4.2.1 supports yinya in nominal predicate readings; nyaji-l is retained visually as see/saw with pronoun A forms ngayu, yundu, and jana.",
        command="dictionary.yaml/grammar.md exact readback; accepted corpus pattern readback; sqlite duplicate preflight",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail="Rule 200 is construction consolidation, not new tree lexicon. It admits distal yinya before and after a bare tree noun, plus object-demonstrative perception frames. It explicitly excludes proximal yala/yanyu decisions and all tree-use/source-prose semantics.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="duplicate-preflight",
        actor="claude-main",
        detail="Exact duplicate preflight over all 50 planned distal-demonstrative tree-reference surfaces returned no accepted/revised/under_review collisions.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_242.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guard passed: exactly 50 unique surfaces; exactly one tree target per row; yinya in every row; all target heads bare; no yala/yanyu; no loans; no denied source-prose tokens; and correct frame distribution for preposed yinya, postposed yinya, and visual nyaji-l perception rows.",
        command="python3 batch_scripts/bank_242.py pre-bank scan",
        artifact_path="batch_scripts/bank_242.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (
                batch_id,
                seq,
                english,
                kuku,
                analysis,
                frame,
                tier,
                words_used,
                loans_used,
                evidence,
                "under_review",
                confidence,
                "claude",
                NOW,
                NOW,
            )
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

    count = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=?", (batch_id,)).fetchone()[0]
    under_review = db.execute(
        "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'",
        (batch_id,),
    ).fetchone()[0]
    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    print(f"banked {LABEL}: rows={count}, under_review={under_review}, verified_before_close={verified}")
    return 0


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