#!/usr/bin/env python3
"""Bank batch-250: Rule 208 low-coverage tree reference lexical expansion."""

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-250"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-250-low-coverage-tree-reference-lexical-expansion-after-rule207-process.md"

TARGET_HEADS = {
    "banday": "cherry-like tree",
    "bijan": "ti tree",
    "bukunjarra": "bukunjarra tree",
    "bulngkarr": "lady apple tree",
    "wanakan": "wanakan tree",
    "warka": "messmate tree",
    "wulngkurr": "stringybark tree",
    "yalngkal": "white wattle",
    "yarun": "black wattle",
    "yumba": "wattle tree",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "kari", "yala", "yanyu", "nyaji-l", "nyajil", "nyajin", "nuka", "nukal", "nukan",
    "mani", "manil", "manin", "muja", "mujal", "mujan", "dunga", "dungay", "dungan",
    "kada", "kaday", "kadan", "wuna", "wunay", "wunan", "bawa", "bawal", "bawan",
    "waju", "wajul", "wajun", "yijarri", "yijarril", "yijarrin", "karrba", "karrbal",
    "karrban", "kuni", "kunil", "kunin", "jurrnga", "jurrngal", "jurrngan", "nanda",
    "nandal", "nandan", "baja", "bajaku", "bila", "bana", "mayi", "diburr", "yirmbal",
    "bubu", "ngara", "nganjirr", "wankar", "nyumbil", "yurrunji", "wanjabu",
}
DENY_ENGLISH = (
    "fruit", "edible", "eat", "eating", "food", "ripe", "ripening", "season", "seed", "nut",
    "flower", "flowers", "blossom", "medicine", "medicinal", "sore", "boil", "wash", "bark",
    "wood", "timber", "source", "material", "use", "uses", "used", "using", "make", "made",
    "making", "roof", "painting", "canoe", "woomera", "spear", "burn", "burning", "cook",
    "cooking", "roast", "roasting", "leach", "leaching", "gather", "gathering", "grow", "grows",
    "growing", "scrub", "beach", "water", "place", "story", "country", "owner", "own", "belongs",
    "thunder", "storm", "ceremony", "magic", "mourning", "dead", "body",
)


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, 2, js(words), js([]), evidence, "0.86")


ROWS = [
    row(1, "The cherry-like tree is here.", "Banday yaluy.", "banday yaluy | cherry.like.tree here", "r208_deictic_here_banday", ["banday", "yaluy"], "Dictionary banday noun 'cherry-like tree'; Patz §3.7 yaluy 'here'."),
    row(2, "The ti tree is here.", "Bijan yaluy.", "bijan yaluy | ti.tree here", "r208_deictic_here_bijan", ["bijan", "yaluy"], "Dictionary bijan noun 'ti tree'; Patz §3.7 yaluy 'here'."),
    row(3, "The bukunjarra tree is here.", "Bukunjarra yaluy.", "bukunjarra yaluy | bukunjarra.tree here", "r208_deictic_here_bukunjarra", ["bukunjarra", "yaluy"], "Dictionary bukunjarra noun tree species; Patz §3.7 yaluy 'here'."),
    row(4, "The lady apple tree is here.", "Bulngkarr yaluy.", "bulngkarr yaluy | lady.apple.tree here", "r208_deictic_here_bulngkarr", ["bulngkarr", "yaluy"], "Dictionary bulngkarr noun 'lady apple'; commentary treats as lady apple tree; Patz §3.7 yaluy."),
    row(5, "The wanakan tree is here.", "Wanakan yaluy.", "wanakan yaluy | wanakan.tree here", "r208_deictic_here_wanakan", ["wanakan", "yaluy"], "Dictionary wanakan noun tree species; selected reference label only; Patz §3.7 yaluy."),
    row(6, "The messmate tree is here.", "Warka yaluy.", "warka yaluy | messmate.tree here", "r208_deictic_here_warka", ["warka", "yaluy"], "Dictionary warka noun 'messmate'/'tree'; selected messmate tree; Patz §3.7 yaluy."),
    row(7, "The stringybark tree is here.", "Wulngkurr yaluy.", "wulngkurr yaluy | stringybark.tree here", "r208_deictic_here_wulngkurr", ["wulngkurr", "yaluy"], "Dictionary wulngkurr noun 'stringy bark tree'; Patz §3.7 yaluy."),
    row(8, "The white wattle is here.", "Yalngkal yaluy.", "yalngkal yaluy | white.wattle here", "r208_deictic_here_yalngkal", ["yalngkal", "yaluy"], "Dictionary yalngkal noun 'white wattle'; Patz §3.7 yaluy."),
    row(9, "The black wattle is here.", "Yarun yaluy.", "yarun yaluy | black.wattle here", "r208_deictic_here_yarun", ["yarun", "yaluy"], "Dictionary yarun noun 'black wattle'; Patz §3.7 yaluy."),
    row(10, "The wattle tree is here.", "Yumba yaluy.", "yumba yaluy | wattle.tree here", "r208_deictic_here_yumba", ["yumba", "yaluy"], "Dictionary yumba noun 'wattle tree'; Patz §3.7 yaluy."),
    row(11, "The cherry-like tree is there.", "Banday yinyay.", "banday yinyay | cherry.like.tree there", "r208_deictic_there_banday", ["banday", "yinyay"], "Dictionary banday noun 'cherry-like tree'; Patz §3.7 yinyay 'there'."),
    row(12, "The ti tree is there.", "Bijan yinyay.", "bijan yinyay | ti.tree there", "r208_deictic_there_bijan", ["bijan", "yinyay"], "Dictionary bijan noun 'ti tree'; Patz §3.7 yinyay 'there'."),
    row(13, "The bukunjarra tree is there.", "Bukunjarra yinyay.", "bukunjarra yinyay | bukunjarra.tree there", "r208_deictic_there_bukunjarra", ["bukunjarra", "yinyay"], "Dictionary bukunjarra noun tree species; Patz §3.7 yinyay."),
    row(14, "The lady apple tree is there.", "Bulngkarr yinyay.", "bulngkarr yinyay | lady.apple.tree there", "r208_deictic_there_bulngkarr", ["bulngkarr", "yinyay"], "Dictionary bulngkarr noun 'lady apple'; selected tree reference; Patz §3.7 yinyay."),
    row(15, "The wanakan tree is there.", "Wanakan yinyay.", "wanakan yinyay | wanakan.tree there", "r208_deictic_there_wanakan", ["wanakan", "yinyay"], "Dictionary wanakan noun tree species; Patz §3.7 yinyay."),
    row(16, "The messmate tree is there.", "Warka yinyay.", "warka yinyay | messmate.tree there", "r208_deictic_there_warka", ["warka", "yinyay"], "Dictionary warka noun 'messmate'/'tree'; Patz §3.7 yinyay."),
    row(17, "The stringybark tree is there.", "Wulngkurr yinyay.", "wulngkurr yinyay | stringybark.tree there", "r208_deictic_there_wulngkurr", ["wulngkurr", "yinyay"], "Dictionary wulngkurr noun 'stringy bark tree'; Patz §3.7 yinyay."),
    row(18, "The white wattle is there.", "Yalngkal yinyay.", "yalngkal yinyay | white.wattle there", "r208_deictic_there_yalngkal", ["yalngkal", "yinyay"], "Dictionary yalngkal noun 'white wattle'; Patz §3.7 yinyay."),
    row(19, "The black wattle is there.", "Yarun yinyay.", "yarun yinyay | black.wattle there", "r208_deictic_there_yarun", ["yarun", "yinyay"], "Dictionary yarun noun 'black wattle'; Patz §3.7 yinyay."),
    row(20, "The wattle tree is there.", "Yumba yinyay.", "yumba yinyay | wattle.tree there", "r208_deictic_there_yumba", ["yumba", "yinyay"], "Dictionary yumba noun 'wattle tree'; Patz §3.7 yinyay."),
    row(21, "That cherry-like tree is there.", "Yinya banday yinyay.", "yinya banday yinyay | that cherry.like.tree there", "r208_initial_that_there_banday", ["yinya", "banday", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; banday tree reference; yinyay there."),
    row(22, "That ti tree is there.", "Yinya bijan yinyay.", "yinya bijan yinyay | that ti.tree there", "r208_initial_that_there_bijan", ["yinya", "bijan", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; bijan ti tree; yinyay there."),
    row(23, "That bukunjarra tree is there.", "Yinya bukunjarra yinyay.", "yinya bukunjarra yinyay | that bukunjarra.tree there", "r208_initial_that_there_bukunjarra", ["yinya", "bukunjarra", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; bukunjarra tree; yinyay there."),
    row(24, "That lady apple tree is there.", "Yinya bulngkarr yinyay.", "yinya bulngkarr yinyay | that lady.apple.tree there", "r208_initial_that_there_bulngkarr", ["yinya", "bulngkarr", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; bulngkarr tree; yinyay there."),
    row(25, "That wanakan tree is there.", "Yinya wanakan yinyay.", "yinya wanakan yinyay | that wanakan.tree there", "r208_initial_that_there_wanakan", ["yinya", "wanakan", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; wanakan tree; yinyay there."),
    row(26, "That messmate tree is there.", "Yinya warka yinyay.", "yinya warka yinyay | that messmate.tree there", "r208_initial_that_there_warka", ["yinya", "warka", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; warka messmate; yinyay there."),
    row(27, "That stringybark tree is there.", "Yinya wulngkurr yinyay.", "yinya wulngkurr yinyay | that stringybark.tree there", "r208_initial_that_there_wulngkurr", ["yinya", "wulngkurr", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; wulngkurr tree; yinyay there."),
    row(28, "That white wattle is there.", "Yinya yalngkal yinyay.", "yinya yalngkal yinyay | that white.wattle there", "r208_initial_that_there_yalngkal", ["yinya", "yalngkal", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; yalngkal white wattle; yinyay there."),
    row(29, "That black wattle is there.", "Yinya yarun yinyay.", "yinya yarun yinyay | that black.wattle there", "r208_initial_that_there_yarun", ["yinya", "yarun", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; yarun black wattle; yinyay there."),
    row(30, "That wattle tree is there.", "Yinya yumba yinyay.", "yinya yumba yinyay | that wattle.tree there", "r208_initial_that_there_yumba", ["yinya", "yumba", "yinyay"], "Patz §3.7 yinya can co-occur with a noun; yumba wattle tree; yinyay there."),
    row(31, "That cherry-like tree is there.", "Banday yinya yinyay.", "banday yinya yinyay | cherry.like.tree that there", "r208_postposed_that_there_banday", ["banday", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; banday tree reference; yinyay there."),
    row(32, "That ti tree is there.", "Bijan yinya yinyay.", "bijan yinya yinyay | ti.tree that there", "r208_postposed_that_there_bijan", ["bijan", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; bijan ti tree; yinyay there."),
    row(33, "That bukunjarra tree is there.", "Bukunjarra yinya yinyay.", "bukunjarra yinya yinyay | bukunjarra.tree that there", "r208_postposed_that_there_bukunjarra", ["bukunjarra", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; bukunjarra tree; yinyay there."),
    row(34, "That lady apple tree is there.", "Bulngkarr yinya yinyay.", "bulngkarr yinya yinyay | lady.apple.tree that there", "r208_postposed_that_there_bulngkarr", ["bulngkarr", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; bulngkarr tree; yinyay there."),
    row(35, "That wanakan tree is there.", "Wanakan yinya yinyay.", "wanakan yinya yinyay | wanakan.tree that there", "r208_postposed_that_there_wanakan", ["wanakan", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; wanakan tree; yinyay there."),
    row(36, "That messmate tree is there.", "Warka yinya yinyay.", "warka yinya yinyay | messmate.tree that there", "r208_postposed_that_there_warka", ["warka", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; warka messmate; yinyay there."),
    row(37, "That stringybark tree is there.", "Wulngkurr yinya yinyay.", "wulngkurr yinya yinyay | stringybark.tree that there", "r208_postposed_that_there_wulngkurr", ["wulngkurr", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; wulngkurr tree; yinyay there."),
    row(38, "That white wattle is there.", "Yalngkal yinya yinyay.", "yalngkal yinya yinyay | white.wattle that there", "r208_postposed_that_there_yalngkal", ["yalngkal", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; yalngkal white wattle; yinyay there."),
    row(39, "That black wattle is there.", "Yarun yinya yinyay.", "yarun yinya yinyay | black.wattle that there", "r208_postposed_that_there_yarun", ["yarun", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; yarun black wattle; yinyay there."),
    row(40, "That wattle tree is there.", "Yumba yinya yinyay.", "yumba yinya yinyay | wattle.tree that there", "r208_postposed_that_there_yumba", ["yumba", "yinya", "yinyay"], "Patz §3.7 permits yinya after a noun; yumba wattle tree; yinyay there."),
    row(41, "That cherry-like tree is here.", "Yinya banday yaluy.", "yinya banday yaluy | that cherry.like.tree here", "r208_initial_that_here_banday", ["yinya", "banday", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; banday tree reference; yaluy here."),
    row(42, "That ti tree is here.", "Yinya bijan yaluy.", "yinya bijan yaluy | that ti.tree here", "r208_initial_that_here_bijan", ["yinya", "bijan", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; bijan ti tree; yaluy here."),
    row(43, "That bukunjarra tree is here.", "Yinya bukunjarra yaluy.", "yinya bukunjarra yaluy | that bukunjarra.tree here", "r208_initial_that_here_bukunjarra", ["yinya", "bukunjarra", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; bukunjarra tree; yaluy here."),
    row(44, "That lady apple tree is here.", "Yinya bulngkarr yaluy.", "yinya bulngkarr yaluy | that lady.apple.tree here", "r208_initial_that_here_bulngkarr", ["yinya", "bulngkarr", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; bulngkarr tree; yaluy here."),
    row(45, "That wanakan tree is here.", "Yinya wanakan yaluy.", "yinya wanakan yaluy | that wanakan.tree here", "r208_initial_that_here_wanakan", ["yinya", "wanakan", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; wanakan tree; yaluy here."),
    row(46, "That messmate tree is here.", "Yinya warka yaluy.", "yinya warka yaluy | that messmate.tree here", "r208_initial_that_here_warka", ["yinya", "warka", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; warka messmate; yaluy here."),
    row(47, "That stringybark tree is here.", "Yinya wulngkurr yaluy.", "yinya wulngkurr yaluy | that stringybark.tree here", "r208_initial_that_here_wulngkurr", ["yinya", "wulngkurr", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; wulngkurr tree; yaluy here."),
    row(48, "That white wattle is here.", "Yinya yalngkal yaluy.", "yinya yalngkal yaluy | that white.wattle here", "r208_initial_that_here_yalngkal", ["yinya", "yalngkal", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; yalngkal white wattle; yaluy here."),
    row(49, "That black wattle is here.", "Yinya yarun yaluy.", "yinya yarun yaluy | that black.wattle here", "r208_initial_that_here_yarun", ["yinya", "yarun", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; yarun black wattle; yaluy here."),
    row(50, "That wattle tree is here.", "Yinya yumba yaluy.", "yinya yumba yaluy | that wattle.tree here", "r208_initial_that_here_yumba", ["yinya", "yumba", "yaluy"], "Patz §3.7 yinya can co-occur with a noun; yumba wattle tree; yaluy here."),
]


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("r208_"):
            issues.append(f"{label}: Rule 208 frame must start with r208_")
        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 208")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied carry-forward 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 208 target noun, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            dotted = selected.replace("-", ".").replace(" ", ".")
            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 not in analysis and dotted not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        for support in SUPPORT:
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if 1 <= seq <= 10 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.")):
            issues.append(f"{label}: rows 1-10 require TARGET yaluy")
        if 11 <= seq <= 20 and (has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 11-20 require TARGET yinyay")
        if 21 <= seq <= 30 and (not low.startswith("yinya ") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 21-30 require Yinya TARGET yinyay")
        if 31 <= seq <= 40 and (has_token(low, "yaluy") or not has_token(low, "yinya") or not low.endswith(" yinyay.") or low.startswith("yinya ")):
            issues.append(f"{label}: rows 31-40 require TARGET yinya yinyay")
        if 41 <= seq <= 50 and (not low.startswith("yinya ") or has_token(low, "yinyay") or not low.endswith(" yaluy.")):
            issues.append(f"{label}: rows 41-50 require Yinya TARGET yaluy")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied plant-use/source/ecology/social 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 208 draft: low-coverage tree reference lexical expansion after Rule 207",
                "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

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, *row_data[:-1], "under_review", row_data[-1], "claude", NOW)
            for row_data in ROWS
        ],
    )
    verified_before, words_before = db.execute(
        """
        SELECT COUNT(*), SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail="Checked Patz §3.7 demonstrative frames plus dictionary entries for banday, bijan, bukunjarra, bulngkarr, wanakan, warka, wulngkurr, yalngkal, yarun, and yumba. Selected only bare tree-reference readings.",
        command="rg/sed dictionary.yaml and grammar.md around selected entries and demonstrative grammar",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail="Deferred older tree heads with accepted simple deictic collisions; corrected misspelled bugunjara to source-backed bukunjarra; avoided polysemous/homograph/story-heavy and use-heavy plant entries.",
        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 Rule 208 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="sqlite3 duplicate-preflight over planned surfaces",
        output_excerpt="No 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="bank_250.py static guards passed: 50 explicit rows, exactly one tree target noun per row, support words recorded, correct five frame bands, no target morphology, no denied plant-use/source/ecology English/Kuku fields, no loans.",
        artifact_path="batch_scripts/bank_250.py",
        created_at=NOW,
    )
    db.commit()
    print(f"banked {LABEL}: rows=50, under_review=50, verified_before_close={verified_before}, words_before={words_before}")
    return 0


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