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

TARGET_HEADS = {
    "barinkan": "scrub bird",
    "bilu-warra": "spoon bill",
    "bujil-yiran": "straw-necked ibis",
    "kalmbangarr": "black diver bird",
    "dijarrdijin": "willie wagtail",
    "dukunjuju": "golden whistler",
    "jiwal-jiwal": "kingfisher",
    "karrmbil": "blue mountain parakeet",
    "kujuway": "brown pigeon",
    "yiki": "owl",
}
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",
    "dabway", "dakwul-dakwul", "dakwurr-dakwun", "dawadawa", "dawa-dawa", "dirrmbay", "jiway", "jukujuku",
    "kurri-kurri", "kurrujuwa", "mulumu", "walu-dalbaji",
    "balar", "ngajal", "walngka", "yilki", "jirka", "yiri", "yirri", "marrka", "mulngku", "miral",
}
DENY_ENGLISH = (
    "fly", "flying", "sing", "singing", "call", "calling", "warn", "warning", "message", "messenger",
    "totem", "moiety", "sacred", "story", "place", "nest", "egg", "feather", "food", "eat", "eating",
    "hunt", "hunting", "catch", "catching", "dance", "dancing", "display", "corroboree", "storm", "omen",
    "death", "dead", "spirit", "wood", "fire", "throw", "throwing", "stranger", "crocodile", "saw",
    "sound", "hear", "heard", "morning", "river", "bank", "country", "owner", "own", "belongs",
)


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 scrub bird is here.", "Barinkan yaluy.", "barinkan yaluy | scrub.bird here", "r211_deictic_here_barinkan", ["barinkan", "yaluy"], "Dictionary barinkan noun 'scrub bird, dark grey with white breast'; Patz section 3.7 yaluy 'here'."),
    row(2, "The spoon bill is here.", "Bilu-warra yaluy.", "bilu-warra yaluy | spoon.bill here", "r211_deictic_here_bilu_warra", ["bilu-warra", "yaluy"], "Dictionary bilu-warra noun 'spoon bill'; Patz section 3.7 yaluy 'here'."),
    row(3, "The straw-necked ibis is here.", "Bujil-yiran yaluy.", "bujil-yiran yaluy | straw.necked.ibis here", "r211_deictic_here_bujil_yiran", ["bujil-yiran", "yaluy"], "Dictionary bujil-yiran noun 'straw-necked ibis'; Patz section 3.7 yaluy 'here'."),
    row(4, "The black diver bird is here.", "Kalmbangarr yaluy.", "kalmbangarr yaluy | black.diver.bird here", "r211_deictic_here_kalmbangarr", ["kalmbangarr", "yaluy"], "Dictionary kalmbangarr noun 'black diver bird'; selected after dawadawa failed the unhyphenated-reduplication lint guard; Patz section 3.7 yaluy."),
    row(5, "The willie wagtail is here.", "Dijarrdijin yaluy.", "dijarrdijin yaluy | willie.wagtail here", "r211_deictic_here_dijarrdijin", ["dijarrdijin", "yaluy"], "Dictionary dijarrdijin noun 'willie wagtail'; Patz section 3.7 yaluy 'here'."),
    row(6, "The golden whistler is here.", "Dukunjuju yaluy.", "dukunjuju yaluy | golden.whistler here", "r211_deictic_here_dukunjuju", ["dukunjuju", "yaluy"], "Dictionary dukunjuju noun 'golden whistler' by definition; gloss typo 'golder' closed; Patz section 3.7 yaluy."),
    row(7, "The kingfisher is here.", "Jiwal-jiwal yaluy.", "jiwal-jiwal yaluy | kingfisher here", "r211_deictic_here_jiwal_jiwal", ["jiwal-jiwal", "yaluy"], "Dictionary jiwal-jiwal noun 'kingfisher, white tailed'; selected kingfisher label only; Patz section 3.7 yaluy."),
    row(8, "The blue mountain parakeet is here.", "Karrmbil yaluy.", "karrmbil yaluy | blue.mountain.parakeet here", "r211_deictic_here_karrmbil", ["karrmbil", "yaluy"], "Dictionary karrmbil noun 'blue mountain parakeet'; Patz section 3.7 yaluy 'here'."),
    row(9, "The brown pigeon is here.", "Kujuway yaluy.", "kujuway yaluy | brown.pigeon here", "r211_deictic_here_kujuway", ["kujuway", "yaluy"], "Dictionary kujuway noun 'brown pigeon'; brown-and-green detail closed; Patz section 3.7 yaluy."),
    row(10, "The owl is here.", "Yiki yaluy.", "yiki yaluy | owl here", "r211_deictic_here_yiki", ["yiki", "yaluy"], "Dictionary yiki noun 'owl'; night-owl detail closed; Patz section 3.7 yaluy 'here'."),
    row(11, "The scrub bird is there.", "Barinkan yinyay.", "barinkan yinyay | scrub.bird there", "r211_deictic_there_barinkan", ["barinkan", "yinyay"], "Dictionary barinkan noun 'scrub bird'; Patz section 3.7 yinyay 'there'."),
    row(12, "The spoon bill is there.", "Bilu-warra yinyay.", "bilu-warra yinyay | spoon.bill there", "r211_deictic_there_bilu_warra", ["bilu-warra", "yinyay"], "Dictionary bilu-warra noun 'spoon bill'; Patz section 3.7 yinyay 'there'."),
    row(13, "The straw-necked ibis is there.", "Bujil-yiran yinyay.", "bujil-yiran yinyay | straw.necked.ibis there", "r211_deictic_there_bujil_yiran", ["bujil-yiran", "yinyay"], "Dictionary bujil-yiran noun 'straw-necked ibis'; Patz section 3.7 yinyay."),
    row(14, "The black diver bird is there.", "Kalmbangarr yinyay.", "kalmbangarr yinyay | black.diver.bird there", "r211_deictic_there_kalmbangarr", ["kalmbangarr", "yinyay"], "Dictionary kalmbangarr noun 'black diver bird'; Patz section 3.7 yinyay 'there'."),
    row(15, "The willie wagtail is there.", "Dijarrdijin yinyay.", "dijarrdijin yinyay | willie.wagtail there", "r211_deictic_there_dijarrdijin", ["dijarrdijin", "yinyay"], "Dictionary dijarrdijin noun 'willie wagtail'; Patz section 3.7 yinyay."),
    row(16, "The golden whistler is there.", "Dukunjuju yinyay.", "dukunjuju yinyay | golden.whistler there", "r211_deictic_there_dukunjuju", ["dukunjuju", "yinyay"], "Dictionary dukunjuju noun 'golden whistler' by definition; Patz section 3.7 yinyay."),
    row(17, "The kingfisher is there.", "Jiwal-jiwal yinyay.", "jiwal-jiwal yinyay | kingfisher there", "r211_deictic_there_jiwal_jiwal", ["jiwal-jiwal", "yinyay"], "Dictionary jiwal-jiwal noun 'kingfisher'; Patz section 3.7 yinyay 'there'."),
    row(18, "The blue mountain parakeet is there.", "Karrmbil yinyay.", "karrmbil yinyay | blue.mountain.parakeet there", "r211_deictic_there_karrmbil", ["karrmbil", "yinyay"], "Dictionary karrmbil noun 'blue mountain parakeet'; Patz section 3.7 yinyay."),
    row(19, "The brown pigeon is there.", "Kujuway yinyay.", "kujuway yinyay | brown.pigeon there", "r211_deictic_there_kujuway", ["kujuway", "yinyay"], "Dictionary kujuway noun 'brown pigeon'; Patz section 3.7 yinyay 'there'."),
    row(20, "The owl is there.", "Yiki yinyay.", "yiki yinyay | owl there", "r211_deictic_there_yiki", ["yiki", "yinyay"], "Dictionary yiki noun 'owl'; Patz section 3.7 yinyay 'there'."),
    row(21, "That scrub bird is there.", "Yinya barinkan yinyay.", "yinya barinkan yinyay | that scrub.bird there", "r211_initial_that_there_barinkan", ["yinya", "barinkan", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; barinkan scrub bird; yinyay there."),
    row(22, "That spoon bill is there.", "Yinya bilu-warra yinyay.", "yinya bilu-warra yinyay | that spoon.bill there", "r211_initial_that_there_bilu_warra", ["yinya", "bilu-warra", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; bilu-warra spoon bill; yinyay there."),
    row(23, "That straw-necked ibis is there.", "Yinya bujil-yiran yinyay.", "yinya bujil-yiran yinyay | that straw.necked.ibis there", "r211_initial_that_there_bujil_yiran", ["yinya", "bujil-yiran", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; bujil-yiran straw-necked ibis; yinyay there."),
    row(24, "That black diver bird is there.", "Yinya kalmbangarr yinyay.", "yinya kalmbangarr yinyay | that black.diver.bird there", "r211_initial_that_there_kalmbangarr", ["yinya", "kalmbangarr", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; kalmbangarr black diver bird; yinyay there."),
    row(25, "That willie wagtail is there.", "Yinya dijarrdijin yinyay.", "yinya dijarrdijin yinyay | that willie.wagtail there", "r211_initial_that_there_dijarrdijin", ["yinya", "dijarrdijin", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dijarrdijin willie wagtail; yinyay there."),
    row(26, "That golden whistler is there.", "Yinya dukunjuju yinyay.", "yinya dukunjuju yinyay | that golden.whistler there", "r211_initial_that_there_dukunjuju", ["yinya", "dukunjuju", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dukunjuju golden whistler; yinyay there."),
    row(27, "That kingfisher is there.", "Yinya jiwal-jiwal yinyay.", "yinya jiwal-jiwal yinyay | that kingfisher there", "r211_initial_that_there_jiwal_jiwal", ["yinya", "jiwal-jiwal", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; jiwal-jiwal kingfisher; yinyay there."),
    row(28, "That blue mountain parakeet is there.", "Yinya karrmbil yinyay.", "yinya karrmbil yinyay | that blue.mountain.parakeet there", "r211_initial_that_there_karrmbil", ["yinya", "karrmbil", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; karrmbil blue mountain parakeet; yinyay there."),
    row(29, "That brown pigeon is there.", "Yinya kujuway yinyay.", "yinya kujuway yinyay | that brown.pigeon there", "r211_initial_that_there_kujuway", ["yinya", "kujuway", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; kujuway brown pigeon; yinyay there."),
    row(30, "That owl is there.", "Yinya yiki yinyay.", "yinya yiki yinyay | that owl there", "r211_initial_that_there_yiki", ["yinya", "yiki", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; yiki owl; yinyay there."),
    row(31, "That scrub bird is there.", "Barinkan yinya yinyay.", "barinkan yinya yinyay | scrub.bird that there", "r211_postposed_that_there_barinkan", ["barinkan", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; barinkan scrub bird; yinyay there."),
    row(32, "That spoon bill is there.", "Bilu-warra yinya yinyay.", "bilu-warra yinya yinyay | spoon.bill that there", "r211_postposed_that_there_bilu_warra", ["bilu-warra", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; bilu-warra spoon bill; yinyay there."),
    row(33, "That straw-necked ibis is there.", "Bujil-yiran yinya yinyay.", "bujil-yiran yinya yinyay | straw.necked.ibis that there", "r211_postposed_that_there_bujil_yiran", ["bujil-yiran", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; bujil-yiran straw-necked ibis; yinyay there."),
    row(34, "That black diver bird is there.", "Kalmbangarr yinya yinyay.", "kalmbangarr yinya yinyay | black.diver.bird that there", "r211_postposed_that_there_kalmbangarr", ["kalmbangarr", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; kalmbangarr black diver bird; yinyay there."),
    row(35, "That willie wagtail is there.", "Dijarrdijin yinya yinyay.", "dijarrdijin yinya yinyay | willie.wagtail that there", "r211_postposed_that_there_dijarrdijin", ["dijarrdijin", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; dijarrdijin willie wagtail; yinyay there."),
    row(36, "That golden whistler is there.", "Dukunjuju yinya yinyay.", "dukunjuju yinya yinyay | golden.whistler that there", "r211_postposed_that_there_dukunjuju", ["dukunjuju", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; dukunjuju golden whistler; yinyay there."),
    row(37, "That kingfisher is there.", "Jiwal-jiwal yinya yinyay.", "jiwal-jiwal yinya yinyay | kingfisher that there", "r211_postposed_that_there_jiwal_jiwal", ["jiwal-jiwal", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; jiwal-jiwal kingfisher; yinyay there."),
    row(38, "That blue mountain parakeet is there.", "Karrmbil yinya yinyay.", "karrmbil yinya yinyay | blue.mountain.parakeet that there", "r211_postposed_that_there_karrmbil", ["karrmbil", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; karrmbil blue mountain parakeet; yinyay there."),
    row(39, "That brown pigeon is there.", "Kujuway yinya yinyay.", "kujuway yinya yinyay | brown.pigeon that there", "r211_postposed_that_there_kujuway", ["kujuway", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; kujuway brown pigeon; yinyay there."),
    row(40, "That owl is there.", "Yiki yinya yinyay.", "yiki yinya yinyay | owl that there", "r211_postposed_that_there_yiki", ["yiki", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; yiki owl; yinyay there."),
    row(41, "That scrub bird is here.", "Yinya barinkan yaluy.", "yinya barinkan yaluy | that scrub.bird here", "r211_initial_that_here_barinkan", ["yinya", "barinkan", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; barinkan scrub bird; yaluy here."),
    row(42, "That spoon bill is here.", "Yinya bilu-warra yaluy.", "yinya bilu-warra yaluy | that spoon.bill here", "r211_initial_that_here_bilu_warra", ["yinya", "bilu-warra", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; bilu-warra spoon bill; yaluy here."),
    row(43, "That straw-necked ibis is here.", "Yinya bujil-yiran yaluy.", "yinya bujil-yiran yaluy | that straw.necked.ibis here", "r211_initial_that_here_bujil_yiran", ["yinya", "bujil-yiran", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; bujil-yiran straw-necked ibis; yaluy here."),
    row(44, "That black diver bird is here.", "Yinya kalmbangarr yaluy.", "yinya kalmbangarr yaluy | that black.diver.bird here", "r211_initial_that_here_kalmbangarr", ["yinya", "kalmbangarr", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; kalmbangarr black diver bird; yaluy here."),
    row(45, "That willie wagtail is here.", "Yinya dijarrdijin yaluy.", "yinya dijarrdijin yaluy | that willie.wagtail here", "r211_initial_that_here_dijarrdijin", ["yinya", "dijarrdijin", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; dijarrdijin willie wagtail; yaluy here."),
    row(46, "That golden whistler is here.", "Yinya dukunjuju yaluy.", "yinya dukunjuju yaluy | that golden.whistler here", "r211_initial_that_here_dukunjuju", ["yinya", "dukunjuju", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; dukunjuju golden whistler; yaluy here."),
    row(47, "That kingfisher is here.", "Yinya jiwal-jiwal yaluy.", "yinya jiwal-jiwal yaluy | that kingfisher here", "r211_initial_that_here_jiwal_jiwal", ["yinya", "jiwal-jiwal", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; jiwal-jiwal kingfisher; yaluy here."),
    row(48, "That blue mountain parakeet is here.", "Yinya karrmbil yaluy.", "yinya karrmbil yaluy | that blue.mountain.parakeet here", "r211_initial_that_here_karrmbil", ["yinya", "karrmbil", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; karrmbil blue mountain parakeet; yaluy here."),
    row(49, "That brown pigeon is here.", "Yinya kujuway yaluy.", "yinya kujuway yaluy | that brown.pigeon here", "r211_initial_that_here_kujuway", ["yinya", "kujuway", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; kujuway brown pigeon; yaluy here."),
    row(50, "That owl is here.", "Yinya yiki yaluy.", "yinya yiki yaluy | that owl here", "r211_initial_that_here_yiki", ["yinya", "yiki", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; yiki owl; 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("r211_"):
            issues.append(f"{label}: Rule 211 frame must start with r211_")
        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 211")
        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 211 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 bird-behavior/story/use 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 211 draft: low-coverage bird reference lexical expansion after Rule 210",
                "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-bird entries for barinkan, bilu-warra, bujil-yiran, kalmbangarr, dijarrdijin, dukunjuju, jiwal-jiwal, karrmbil, kujuway, and yiki. Selected only bare bird-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="Rejected place-name, body-part, fauna-fish, and too-small shelter-dwelling fields; rejected bird candidates carrying messenger, totem, dance/display, warning, death/omen, storm/mythical, crocodile-warning, sacred-corroboree wood, place/story, calling prose, or unhyphenated reduplication lint risk.",
        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 211 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_253.py static guards passed: 50 explicit hand-authored rows, exactly one bird target noun per row, support words recorded, correct five frame bands, no target morphology, no loans, and no denied bird-behavior/story/use English/Kuku fields.",
        artifact_path="batch_scripts/bank_253.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())
