#!/usr/bin/env python3
"""Bank batch-211: Rule 169 insect reference lexical expansion after Rule 168."""

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

TARGET_HEADS = {
    "biray": "grey march fly",
    "kamay": "yellow march fly",
    "manukurru": "scorpion",
    "mindil": "dog flea",
    "murrmun": "rhinoceros beetle",
    "murrumun": "black beetle",
    "muyu-muyu": "small red ant",
    "wurrarr-wurrarr": "mud wasp",
    "yijil-yijin": "cricket",
    "yinja-yinja": "cicada",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "bayka", "baykal", "baykan", "yinbay", "yungka", "yungal", "nuka", "nukan", "waju", "wajun",
    "mani", "manin", "daji", "dajin", "dunga", "dungan", "wandi", "wandin", "baya", "kubu", "bubu",
    "diri-diri", "wurarr-wurarr", "kamu", "jimu", "kinga", "birinjil", "kandal", "mulma", "dabu",
    "kuja", "malal", "nyumbil", "waja", "walbul-walbul", "wunba", "yangka", "kalkamal", "karrkil",
    "kuran", "ngirran", "nyirran",
}
DENY_ENGLISH = (
    "bite", "bites", "bit", "biting", "sting", "stings", "stung", "sick", "sickness", "vomit", "vomited",
    "honey", "nest", "nests", "egg", "eggs", "larva", "larvae", "edible", "eat", "eats", "ate", "food",
    "medicine", "heal", "healed", "season", "seasonal", "totem", "moiety", "life force", "crow", "stingray",
    "flying fish", "mangrove", "store", "swarm", "swarmed", "pest", "control", "danger", "dangerous",
)


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


ROWS = [
    row(1, "The grey March fly is here.", "Biray yaluy.", "biray yaluy | grey.march.fly here", "r169_deictic_biray_here", ["biray", "yaluy"], "Rule 169 admits biray as grey March fly; reference only."),
    row(2, "The yellow March fly is here.", "Kamay yaluy.", "kamay yaluy | yellow.march.fly here", "r169_deictic_kamay_here", ["kamay", "yaluy"], "Rule 169 admits kamay as yellow March fly; reference only."),
    row(3, "The scorpion is here.", "Manukurru yaluy.", "manukurru yaluy | scorpion here", "r169_deictic_manukurru_here", ["manukurru", "yaluy"], "Rule 169 admits manukurru as scorpion; no sting/danger row."),
    row(4, "The dog flea is here.", "Mindil yaluy.", "mindil yaluy | dog.flea here", "r169_deictic_mindil_here", ["mindil", "yaluy"], "Rule 169 admits mindil as dog flea; reference only."),
    row(5, "The rhinoceros beetle is here.", "Murrmun yaluy.", "murrmun yaluy | rhinoceros.beetle here", "r169_deictic_murrmun_here", ["murrmun", "yaluy"], "Rule 169 admits murrmun as rhinoceros beetle; reference only."),
    row(6, "The black beetle is here.", "Murrumun yaluy.", "murrumun yaluy | black.beetle here", "r169_deictic_murrumun_here", ["murrumun", "yaluy"], "Rule 169 admits murrumun as black beetle; reference only."),
    row(7, "The small red ant is here.", "Muyu-muyu yaluy.", "muyu-muyu yaluy | small.red.ant here", "r169_deictic_muyumuyu_here", ["muyu-muyu", "yaluy"], "Rule 169 admits muyu-muyu as small red ant; reduplicated lexical head."),
    row(8, "The mud wasp is here.", "Wurrarr-wurrarr yaluy.", "wurrarr-wurrarr yaluy | mud.wasp here", "r169_deictic_wurrarrwurrarr_here", ["wurrarr-wurrarr", "yaluy"], "Rule 169 admits wurrarr-wurrarr as mud wasp; no sting/nest row."),
    row(9, "The cricket is here.", "Yijil-yijin yaluy.", "yijil-yijin yaluy | cricket here", "r169_deictic_yijilyijin_here", ["yijil-yijin", "yaluy"], "Rule 169 admits yijil-yijin as cricket; partial reduplicated lexical head."),
    row(10, "The cicada is here.", "Yinja-yinja yaluy.", "yinja-yinja yaluy | cicada here", "r169_deictic_yinjayinja_here", ["yinja-yinja", "yaluy"], "Rule 169 admits yinja-yinja as cicada; reduplicated onomatopoeic lexical head."),
    row(11, "I see the grey March fly.", "Ngayu biray nyajil.", "ngayu biray nyaji-l | I grey.march.fly see-NONPAST", "r169_present_i_biray", ["ngayu", "biray", "nyaji-l"], "Pronoun A bare; biray object bare; no bite/event row."),
    row(12, "I see the yellow March fly.", "Ngayu kamay nyajil.", "ngayu kamay nyaji-l | I yellow.march.fly see-NONPAST", "r169_present_i_kamay", ["ngayu", "kamay", "nyaji-l"], "Pronoun A bare; kamay object bare."),
    row(13, "I see the scorpion.", "Ngayu manukurru nyajil.", "ngayu manukurru nyaji-l | I scorpion see-NONPAST", "r169_present_i_manukurru", ["ngayu", "manukurru", "nyaji-l"], "Pronoun A bare; manukurru object bare; no sting/danger row."),
    row(14, "I see the dog flea.", "Ngayu mindil nyajil.", "ngayu mindil nyaji-l | I dog.flea see-NONPAST", "r169_present_i_mindil", ["ngayu", "mindil", "nyaji-l"], "Pronoun A bare; mindil object bare."),
    row(15, "I see the rhinoceros beetle.", "Ngayu murrmun nyajil.", "ngayu murrmun nyaji-l | I rhinoceros.beetle see-NONPAST", "r169_present_i_murrmun", ["ngayu", "murrmun", "nyaji-l"], "Pronoun A bare; murrmun object bare."),
    row(16, "I see the black beetle.", "Ngayu murrumun nyajil.", "ngayu murrumun nyaji-l | I black.beetle see-NONPAST", "r169_present_i_murrumun", ["ngayu", "murrumun", "nyaji-l"], "Pronoun A bare; murrumun object bare."),
    row(17, "I see the small red ant.", "Ngayu muyu-muyu nyajil.", "ngayu muyu-muyu nyaji-l | I small.red.ant see-NONPAST", "r169_present_i_muyumuyu", ["ngayu", "muyu-muyu", "nyaji-l"], "Pronoun A bare; muyu-muyu object bare."),
    row(18, "I see the mud wasp.", "Ngayu wurrarr-wurrarr nyajil.", "ngayu wurrarr-wurrarr nyaji-l | I mud.wasp see-NONPAST", "r169_present_i_wurrarrwurrarr", ["ngayu", "wurrarr-wurrarr", "nyaji-l"], "Pronoun A bare; wurrarr-wurrarr object bare; no sting/nest row."),
    row(19, "I see the cricket.", "Ngayu yijil-yijin nyajil.", "ngayu yijil-yijin nyaji-l | I cricket see-NONPAST", "r169_present_i_yijilyijin", ["ngayu", "yijil-yijin", "nyaji-l"], "Pronoun A bare; yijil-yijin object bare."),
    row(20, "I see the cicada.", "Ngayu yinja-yinja nyajil.", "ngayu yinja-yinja nyaji-l | I cicada see-NONPAST", "r169_present_i_yinjayinja", ["ngayu", "yinja-yinja", "nyaji-l"], "Pronoun A bare; yinja-yinja object bare."),
    row(21, "You see the grey March fly there.", "Yundu biray yinyay nyajil.", "yundu biray yinyay nyaji-l | you grey.march.fly there see-NONPAST", "r169_present_you_biray_there", ["yundu", "biray", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(22, "You see the yellow March fly there.", "Yundu kamay yinyay nyajil.", "yundu kamay yinyay nyaji-l | you yellow.march.fly there see-NONPAST", "r169_present_you_kamay_there", ["yundu", "kamay", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(23, "You see the scorpion there.", "Yundu manukurru yinyay nyajil.", "yundu manukurru yinyay nyaji-l | you scorpion there see-NONPAST", "r169_present_you_manukurru_there", ["yundu", "manukurru", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no sting/danger row."),
    row(24, "You see the dog flea there.", "Yundu mindil yinyay nyajil.", "yundu mindil yinyay nyaji-l | you dog.flea there see-NONPAST", "r169_present_you_mindil_there", ["yundu", "mindil", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(25, "You see the rhinoceros beetle there.", "Yundu murrmun yinyay nyajil.", "yundu murrmun yinyay nyaji-l | you rhinoceros.beetle there see-NONPAST", "r169_present_you_murrmun_there", ["yundu", "murrmun", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the black beetle there.", "Yundu murrumun yinyay nyajil.", "yundu murrumun yinyay nyaji-l | you black.beetle there see-NONPAST", "r169_present_you_murrumun_there", ["yundu", "murrumun", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the small red ant there.", "Yundu muyu-muyu yinyay nyajil.", "yundu muyu-muyu yinyay nyaji-l | you small.red.ant there see-NONPAST", "r169_present_you_muyumuyu_there", ["yundu", "muyu-muyu", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the mud wasp there.", "Yundu wurrarr-wurrarr yinyay nyajil.", "yundu wurrarr-wurrarr yinyay nyaji-l | you mud.wasp there see-NONPAST", "r169_present_you_wurrarrwurrarr_there", ["yundu", "wurrarr-wurrarr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no sting/nest row."),
    row(29, "You see the cricket there.", "Yundu yijil-yijin yinyay nyajil.", "yundu yijil-yijin yinyay nyaji-l | you cricket there see-NONPAST", "r169_present_you_yijilyijin_there", ["yundu", "yijil-yijin", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the cicada there.", "Yundu yinja-yinja yinyay nyajil.", "yundu yinja-yinja yinyay nyaji-l | you cicada there see-NONPAST", "r169_present_you_yinjayinja_there", ["yundu", "yinja-yinja", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the grey March fly there.", "Jana biray yinyay nyajin.", "jana biray yinyay nyaji-ny | they grey.march.fly there see-PAST", "r169_past_they_biray_there", ["jana", "biray", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception; target bare."),
    row(32, "They saw the yellow March fly there.", "Jana kamay yinyay nyajin.", "jana kamay yinyay nyaji-ny | they yellow.march.fly there see-PAST", "r169_past_they_kamay_there", ["jana", "kamay", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception; target bare."),
    row(33, "They saw the scorpion there.", "Jana manukurru yinyay nyajin.", "jana manukurru yinyay nyaji-ny | they scorpion there see-PAST", "r169_past_they_manukurru_there", ["jana", "manukurru", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no sting/danger row."),
    row(34, "They saw the dog flea there.", "Jana mindil yinyay nyajin.", "jana mindil yinyay nyaji-ny | they dog.flea there see-PAST", "r169_past_they_mindil_there", ["jana", "mindil", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(35, "They saw the rhinoceros beetle there.", "Jana murrmun yinyay nyajin.", "jana murrmun yinyay nyaji-ny | they rhinoceros.beetle there see-PAST", "r169_past_they_murrmun_there", ["jana", "murrmun", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(36, "They saw the black beetle there.", "Jana murrumun yinyay nyajin.", "jana murrumun yinyay nyaji-ny | they black.beetle there see-PAST", "r169_past_they_murrumun_there", ["jana", "murrumun", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(37, "They saw the small red ant there.", "Jana muyu-muyu yinyay nyajin.", "jana muyu-muyu yinyay nyaji-ny | they small.red.ant there see-PAST", "r169_past_they_muyumuyu_there", ["jana", "muyu-muyu", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(38, "They saw the mud wasp there.", "Jana wurrarr-wurrarr yinyay nyajin.", "jana wurrarr-wurrarr yinyay nyaji-ny | they mud.wasp there see-PAST", "r169_past_they_wurrarrwurrarr_there", ["jana", "wurrarr-wurrarr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no sting/nest row."),
    row(39, "They saw the cricket there.", "Jana yijil-yijin yinyay nyajin.", "jana yijil-yijin yinyay nyaji-ny | they cricket there see-PAST", "r169_past_they_yijilyijin_there", ["jana", "yijil-yijin", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(40, "They saw the cicada there.", "Jana yinja-yinja yinyay nyajin.", "jana yinja-yinja yinyay nyaji-ny | they cicada there see-PAST", "r169_past_they_yinjayinja_there", ["jana", "yinja-yinja", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(41, "We see the grey March fly here.", "Ngana biray yaluy nyajil.", "ngana biray yaluy nyaji-l | we grey.march.fly here see-NONPAST", "r169_present_we_biray_here", ["ngana", "biray", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(42, "We see the yellow March fly here.", "Ngana kamay yaluy nyajil.", "ngana kamay yaluy nyaji-l | we yellow.march.fly here see-NONPAST", "r169_present_we_kamay_here", ["ngana", "kamay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(43, "We see the scorpion here.", "Ngana manukurru yaluy nyajil.", "ngana manukurru yaluy nyaji-l | we scorpion here see-NONPAST", "r169_present_we_manukurru_here", ["ngana", "manukurru", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no sting/danger row."),
    row(44, "We see the dog flea here.", "Ngana mindil yaluy nyajil.", "ngana mindil yaluy nyaji-l | we dog.flea here see-NONPAST", "r169_present_we_mindil_here", ["ngana", "mindil", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(45, "We see the rhinoceros beetle here.", "Ngana murrmun yaluy nyajil.", "ngana murrmun yaluy nyaji-l | we rhinoceros.beetle here see-NONPAST", "r169_present_we_murrmun_here", ["ngana", "murrmun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(46, "We see the black beetle here.", "Ngana murrumun yaluy nyajil.", "ngana murrumun yaluy nyaji-l | we black.beetle here see-NONPAST", "r169_present_we_murrumun_here", ["ngana", "murrumun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(47, "We see the small red ant here.", "Ngana muyu-muyu yaluy nyajil.", "ngana muyu-muyu yaluy nyaji-l | we small.red.ant here see-NONPAST", "r169_present_we_muyumuyu_here", ["ngana", "muyu-muyu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(48, "We see the mud wasp here.", "Ngana wurrarr-wurrarr yaluy nyajil.", "ngana wurrarr-wurrarr yaluy nyaji-l | we mud.wasp here see-NONPAST", "r169_present_we_wurrarrwurrarr_here", ["ngana", "wurrarr-wurrarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no sting/nest row."),
    row(49, "We see the cricket here.", "Ngana yijil-yijin yaluy nyajil.", "ngana yijil-yijin yaluy nyaji-l | we cricket here see-NONPAST", "r169_present_we_yijilyijin_here", ["ngana", "yijil-yijin", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(50, "We see the cicada here.", "Ngana yinja-yinja yaluy nyajil.", "ngana yinja-yinja yaluy nyaji-l | we cicada here see-NONPAST", "r169_present_we_yinjayinja_here", ["ngana", "yinja-yinja", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
]


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


def first_word(low: str) -> str:
    return low.split()[0].strip(".,!?;:\"")


def has_target_case(low: str, head: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?: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)\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("r169_"):
            issues.append(f"{label}: Rule 169 frame must start with r169_")
        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 169")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied rejected-insect/use 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 169 target head, 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.replace(" ", ".") not in analysis and selected not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 169 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 169 perception rows must use nyaji-l")
            first = first_word(low)
            if first not in PRONOUN_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun")
            if 11 <= seq <= 20 and first != "ngayu":
                issues.append(f"{label}: rows 11-20 require ngayu")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            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 use/event/polysemy 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 169 draft: insect reference lexical expansion after Rule 168", "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 169 source pass selected ten unused insect/arthropod reference heads: biray, kamay, manukurru, mindil, murrmun, murrumun, muyu-muyu, wurrarr-wurrarr, yijil-yijin, and yinja-yinja. Dictionary exact readback confirmed selected senses. Patz readback found no target-head conflicts and reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Diri-diri, wurarr-wurarr, kamu, jimu, kinga, birinjil, kandal, mulma, dabu, kuja, malal, nyumbil, waja, walbul-walbul, wunba, yangka, kalkamal, karrkil, kuran, ngirran, and nyirran were reviewed but not selected because of prior corpus use or polysemy/use complications.",
                 command="structured dictionary readback; rg grammar readback; sqlite boundary-aware corpus readback",
                 artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="scope", event_type="lexical-scope", actor="claude-main",
                 detail="Rule 169 is a lexical insect-reference pass for ten bare target heads. It excludes biting, stinging, sickness, honey, nests, eggs, larvae, edible use, medicine, totem/moiety, life-force, seasonal signal, ecology, movement, danger, pest-control, target case, target compounds, possession, and event claims.",
                 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 found 50 planned Kuku surfaces, 50 unique within-batch surfaces, and no exact accepted/revised/under_review cross-corpus duplicates.",
                 command="sqlite exact lower(trim(kuku)) duplicate scan before banking", artifact_path="batch_scripts/bank_211.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one Rule 169 insect target per row; all targets bare; no loans; no rejected-insect/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_211.py static scan", artifact_path="batch_scripts/bank_211.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, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()

    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={len(ROWS)}, under_review={under_review}, verified_before_close={verified}")
    return 0


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