#!/usr/bin/env python3
"""Bank batch-254: Rule 212 low-coverage insect 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-254"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-254-low-coverage-insect-reference-lexical-expansion-after-rule211-process.md"

TARGET_HEADS = {
    "balarr": "flea",
    "dijaraban": "mayfly",
    "kalburiji": "bee",
    "mawal": "bee",
    "munudumbun": "scorpion",
    "munyurri": "sandfly",
    "nakawarra": "bee",
    "ngalmnbu": "jumper ant",
    "yarrka": "bee",
    "yiljun": "grasshopper",
}
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", "karrba", "karrbal", "karrban",
    "kuni", "kunil", "kunin", "daya", "dayal", "yirrka", "yirrkal", "yirrkan",
    "baja", "bajaku", "bana", "baral", "bubu", "juku", "kuku", "mayi", "mukirr",
    "bilngkumu", "wubul", "karrkay", "jalbu", "bama", "ngayu", "nyulu", "yundu",
    "dabadaba", "daba-daba", "dujandujan", "dujan-dujan", "kalkamal", "karrkil", "kuran",
    "kurrmaja", "murma", "wurrbu", "nyumbil", "jawurraji", "jiljay", "jingka-jingka", "wurarr-wurarr",
    "barinkan", "bilu-warra", "bujil-yiran", "kalmbangarr", "dijarrdijin", "dukunjuju",
    "jiwal-jiwal", "karrmbil", "kujuway", "yiki",
}
DENY_ENGLISH = (
    "body", "human", "bite", "biting", "bitten", "sting", "stinging", "sick", "sickness", "vomit",
    "vomiting", "larva", "larvae", "egg", "eggs", "honey", "nest", "nests", "edible", "food", "eat",
    "eating", "medicine", "season", "seasonal", "collect", "collecting", "turkey", "antbed", "ant bed",
    "anthill", "ant hill", "grub", "tree", "wood", "green wood", "mountain", "habitat", "pest",
    "control", "totem", "life-force", "dragonfly", "smallest", "bush",
)


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 flea is here.", "Balarr yaluy.", "balarr yaluy | flea here", "r212_deictic_here_balarr", ["balarr", "yaluy"], "Dictionary balarr noun 'flea'; human-body prose closed; Patz section 3.7 yaluy 'here'."),
    row(2, "The mayfly is here.", "Dijaraban yaluy.", "dijaraban yaluy | mayfly here", "r212_deictic_here_dijaraban", ["dijaraban", "yaluy"], "Dictionary dijaraban noun 'mayfly, dragonfly'; selected mayfly label only; Patz section 3.7 yaluy."),
    row(3, "The kalburiji bee is here.", "Kalburiji yaluy.", "kalburiji yaluy | kalburiji.bee here", "r212_deictic_here_kalburiji", ["kalburiji", "yaluy"], "Dictionary kalburiji noun 'bee', species of bee; Patz section 3.7 yaluy 'here'."),
    row(4, "The mawal bee is here.", "Mawal yaluy.", "mawal yaluy | mawal.bee here", "r212_deictic_here_mawal", ["mawal", "yaluy"], "Dictionary mawal noun 'bee', species of bee; Patz section 3.7 yaluy 'here'."),
    row(5, "The scorpion is here.", "Munudumbun yaluy.", "munudumbun yaluy | scorpion here", "r212_deictic_here_munudumbun", ["munudumbun", "yaluy"], "Dictionary munudumbun noun 'scorpion'; Patz section 3.7 yaluy 'here'."),
    row(6, "The sandfly is here.", "Munyurri yaluy.", "munyurri yaluy | sandfly here", "r212_deictic_here_munyurri", ["munyurri", "yaluy"], "Dictionary munyurri noun 'sandfly'; Patz section 3.7 yaluy 'here'."),
    row(7, "The nakawarra bee is here.", "Nakawarra yaluy.", "nakawarra yaluy | nakawarra.bee here", "r212_deictic_here_nakawarra", ["nakawarra", "yaluy"], "Dictionary nakawarra noun 'species of bee'; selected bee label only; Patz section 3.7 yaluy."),
    row(8, "The jumper ant is here.", "Ngalmnbu yaluy.", "ngalmnbu yaluy | jumper.ant here", "r212_deictic_here_ngalmnbu", ["ngalmnbu", "yaluy"], "Dictionary ngalmnbu noun 'jumper ant'; Patz section 3.7 yaluy 'here'."),
    row(9, "The yarrka bee is here.", "Yarrka yaluy.", "yarrka yaluy | yarrka.bee here", "r212_deictic_here_yarrka", ["yarrka", "yaluy"], "Dictionary yarrka noun 'bee'; smallest/bush prose closed; Patz section 3.7 yaluy."),
    row(10, "The grasshopper is here.", "Yiljun yaluy.", "yiljun yaluy | grasshopper here", "r212_deictic_here_yiljun", ["yiljun", "yaluy"], "Dictionary yiljun noun 'grasshopper'; Patz section 3.7 yaluy 'here'."),
    row(11, "The flea is there.", "Balarr yinyay.", "balarr yinyay | flea there", "r212_deictic_there_balarr", ["balarr", "yinyay"], "Dictionary balarr noun 'flea'; Patz section 3.7 yinyay 'there'."),
    row(12, "The mayfly is there.", "Dijaraban yinyay.", "dijaraban yinyay | mayfly there", "r212_deictic_there_dijaraban", ["dijaraban", "yinyay"], "Dictionary dijaraban noun 'mayfly'; dragonfly translation closed; Patz section 3.7 yinyay."),
    row(13, "The kalburiji bee is there.", "Kalburiji yinyay.", "kalburiji yinyay | kalburiji.bee there", "r212_deictic_there_kalburiji", ["kalburiji", "yinyay"], "Dictionary kalburiji noun 'bee'; Patz section 3.7 yinyay 'there'."),
    row(14, "The mawal bee is there.", "Mawal yinyay.", "mawal yinyay | mawal.bee there", "r212_deictic_there_mawal", ["mawal", "yinyay"], "Dictionary mawal noun 'bee'; Patz section 3.7 yinyay 'there'."),
    row(15, "The scorpion is there.", "Munudumbun yinyay.", "munudumbun yinyay | scorpion there", "r212_deictic_there_munudumbun", ["munudumbun", "yinyay"], "Dictionary munudumbun noun 'scorpion'; Patz section 3.7 yinyay."),
    row(16, "The sandfly is there.", "Munyurri yinyay.", "munyurri yinyay | sandfly there", "r212_deictic_there_munyurri", ["munyurri", "yinyay"], "Dictionary munyurri noun 'sandfly'; Patz section 3.7 yinyay 'there'."),
    row(17, "The nakawarra bee is there.", "Nakawarra yinyay.", "nakawarra yinyay | nakawarra.bee there", "r212_deictic_there_nakawarra", ["nakawarra", "yinyay"], "Dictionary nakawarra noun 'species of bee'; Patz section 3.7 yinyay."),
    row(18, "The jumper ant is there.", "Ngalmnbu yinyay.", "ngalmnbu yinyay | jumper.ant there", "r212_deictic_there_ngalmnbu", ["ngalmnbu", "yinyay"], "Dictionary ngalmnbu noun 'jumper ant'; Patz section 3.7 yinyay."),
    row(19, "The yarrka bee is there.", "Yarrka yinyay.", "yarrka yinyay | yarrka.bee there", "r212_deictic_there_yarrka", ["yarrka", "yinyay"], "Dictionary yarrka noun 'bee'; Patz section 3.7 yinyay 'there'."),
    row(20, "The grasshopper is there.", "Yiljun yinyay.", "yiljun yinyay | grasshopper there", "r212_deictic_there_yiljun", ["yiljun", "yinyay"], "Dictionary yiljun noun 'grasshopper'; Patz section 3.7 yinyay."),
    row(21, "That flea is there.", "Yinya balarr yinyay.", "yinya balarr yinyay | that flea there", "r212_initial_that_there_balarr", ["yinya", "balarr", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; balarr flea; yinyay there."),
    row(22, "That mayfly is there.", "Yinya dijaraban yinyay.", "yinya dijaraban yinyay | that mayfly there", "r212_initial_that_there_dijaraban", ["yinya", "dijaraban", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dijaraban mayfly; yinyay there."),
    row(23, "That kalburiji bee is there.", "Yinya kalburiji yinyay.", "yinya kalburiji yinyay | that kalburiji.bee there", "r212_initial_that_there_kalburiji", ["yinya", "kalburiji", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; kalburiji bee; yinyay there."),
    row(24, "That mawal bee is there.", "Yinya mawal yinyay.", "yinya mawal yinyay | that mawal.bee there", "r212_initial_that_there_mawal", ["yinya", "mawal", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; mawal bee; yinyay there."),
    row(25, "That scorpion is there.", "Yinya munudumbun yinyay.", "yinya munudumbun yinyay | that scorpion there", "r212_initial_that_there_munudumbun", ["yinya", "munudumbun", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; munudumbun scorpion; yinyay there."),
    row(26, "That sandfly is there.", "Yinya munyurri yinyay.", "yinya munyurri yinyay | that sandfly there", "r212_initial_that_there_munyurri", ["yinya", "munyurri", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; munyurri sandfly; yinyay there."),
    row(27, "That nakawarra bee is there.", "Yinya nakawarra yinyay.", "yinya nakawarra yinyay | that nakawarra.bee there", "r212_initial_that_there_nakawarra", ["yinya", "nakawarra", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; nakawarra bee; yinyay there."),
    row(28, "That jumper ant is there.", "Yinya ngalmnbu yinyay.", "yinya ngalmnbu yinyay | that jumper.ant there", "r212_initial_that_there_ngalmnbu", ["yinya", "ngalmnbu", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; ngalmnbu jumper ant; yinyay there."),
    row(29, "That yarrka bee is there.", "Yinya yarrka yinyay.", "yinya yarrka yinyay | that yarrka.bee there", "r212_initial_that_there_yarrka", ["yinya", "yarrka", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; yarrka bee; yinyay there."),
    row(30, "That grasshopper is there.", "Yinya yiljun yinyay.", "yinya yiljun yinyay | that grasshopper there", "r212_initial_that_there_yiljun", ["yinya", "yiljun", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; yiljun grasshopper; yinyay there."),
    row(31, "That flea is there.", "Balarr yinya yinyay.", "balarr yinya yinyay | flea that there", "r212_postposed_that_there_balarr", ["balarr", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; balarr flea; yinyay there."),
    row(32, "That mayfly is there.", "Dijaraban yinya yinyay.", "dijaraban yinya yinyay | mayfly that there", "r212_postposed_that_there_dijaraban", ["dijaraban", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; dijaraban mayfly; yinyay there."),
    row(33, "That kalburiji bee is there.", "Kalburiji yinya yinyay.", "kalburiji yinya yinyay | kalburiji.bee that there", "r212_postposed_that_there_kalburiji", ["kalburiji", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; kalburiji bee; yinyay there."),
    row(34, "That mawal bee is there.", "Mawal yinya yinyay.", "mawal yinya yinyay | mawal.bee that there", "r212_postposed_that_there_mawal", ["mawal", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; mawal bee; yinyay there."),
    row(35, "That scorpion is there.", "Munudumbun yinya yinyay.", "munudumbun yinya yinyay | scorpion that there", "r212_postposed_that_there_munudumbun", ["munudumbun", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; munudumbun scorpion; yinyay there."),
    row(36, "That sandfly is there.", "Munyurri yinya yinyay.", "munyurri yinya yinyay | sandfly that there", "r212_postposed_that_there_munyurri", ["munyurri", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; munyurri sandfly; yinyay there."),
    row(37, "That nakawarra bee is there.", "Nakawarra yinya yinyay.", "nakawarra yinya yinyay | nakawarra.bee that there", "r212_postposed_that_there_nakawarra", ["nakawarra", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; nakawarra bee; yinyay there."),
    row(38, "That jumper ant is there.", "Ngalmnbu yinya yinyay.", "ngalmnbu yinya yinyay | jumper.ant that there", "r212_postposed_that_there_ngalmnbu", ["ngalmnbu", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; ngalmnbu jumper ant; yinyay there."),
    row(39, "That yarrka bee is there.", "Yarrka yinya yinyay.", "yarrka yinya yinyay | yarrka.bee that there", "r212_postposed_that_there_yarrka", ["yarrka", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; yarrka bee; yinyay there."),
    row(40, "That grasshopper is there.", "Yiljun yinya yinyay.", "yiljun yinya yinyay | grasshopper that there", "r212_postposed_that_there_yiljun", ["yiljun", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; yiljun grasshopper; yinyay there."),
    row(41, "That flea is here.", "Yinya balarr yaluy.", "yinya balarr yaluy | that flea here", "r212_initial_that_here_balarr", ["yinya", "balarr", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; balarr flea; yaluy here."),
    row(42, "That mayfly is here.", "Yinya dijaraban yaluy.", "yinya dijaraban yaluy | that mayfly here", "r212_initial_that_here_dijaraban", ["yinya", "dijaraban", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; dijaraban mayfly; yaluy here."),
    row(43, "That kalburiji bee is here.", "Yinya kalburiji yaluy.", "yinya kalburiji yaluy | that kalburiji.bee here", "r212_initial_that_here_kalburiji", ["yinya", "kalburiji", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; kalburiji bee; yaluy here."),
    row(44, "That mawal bee is here.", "Yinya mawal yaluy.", "yinya mawal yaluy | that mawal.bee here", "r212_initial_that_here_mawal", ["yinya", "mawal", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; mawal bee; yaluy here."),
    row(45, "That scorpion is here.", "Yinya munudumbun yaluy.", "yinya munudumbun yaluy | that scorpion here", "r212_initial_that_here_munudumbun", ["yinya", "munudumbun", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; munudumbun scorpion; yaluy here."),
    row(46, "That sandfly is here.", "Yinya munyurri yaluy.", "yinya munyurri yaluy | that sandfly here", "r212_initial_that_here_munyurri", ["yinya", "munyurri", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; munyurri sandfly; yaluy here."),
    row(47, "That nakawarra bee is here.", "Yinya nakawarra yaluy.", "yinya nakawarra yaluy | that nakawarra.bee here", "r212_initial_that_here_nakawarra", ["yinya", "nakawarra", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; nakawarra bee; yaluy here."),
    row(48, "That jumper ant is here.", "Yinya ngalmnbu yaluy.", "yinya ngalmnbu yaluy | that jumper.ant here", "r212_initial_that_here_ngalmnbu", ["yinya", "ngalmnbu", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; ngalmnbu jumper ant; yaluy here."),
    row(49, "That yarrka bee is here.", "Yinya yarrka yaluy.", "yinya yarrka yaluy | that yarrka.bee here", "r212_initial_that_here_yarrka", ["yinya", "yarrka", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; yarrka bee; yaluy here."),
    row(50, "That grasshopper is here.", "Yinya yiljun yaluy.", "yinya yiljun yaluy | that grasshopper here", "r212_initial_that_here_yiljun", ["yinya", "yiljun", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; yiljun grasshopper; 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("r212_"):
            issues.append(f"{label}: Rule 212 frame must start with r212_")
        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 212")
        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 212 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 insect-behavior/use/body/ecology 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 212 draft: low-coverage insect reference lexical expansion after Rule 211",
                "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 section 3.7 demonstrative frames plus dictionary fauna-insect entries for balarr, dijaraban, kalburiji, mawal, munudumbun, munyurri, nakawarra, ngalmnbu, yarrka, and yiljun. Selected only bare insect-reference readings.",
        command="structured dictionary.yaml readback plus grammar.md Patz section 3.7 checks",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail="Deferred shellfish/crustacean and shelter-dwelling; rejected tool-implement, physical-property, and bodily-function fields; rejected insect candidates carrying unhyphenated reduplication lint risk, seasonal-signal, bite/sickness, edible larvae, sting/nest, leech/tree polysemy, antbed/grub, honey/eggs, or habitat/use pressure.",
        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 212 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_254.py static guards passed: 50 explicit hand-authored rows, exactly one insect target noun per row, support words recorded, correct five frame bands, no target morphology, no loans, and no denied insect-behavior/use/body/ecology English/Kuku fields.",
        artifact_path="batch_scripts/bank_254.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())
