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

TARGET_HEADS = {
    "kawal": "cooee",
    "ngawungkal": "halloo",
    "ngulnkul": "hum",
    "nyinja": "grunt",
    "wungka": "wail",
    "kandarr": "belch",
    "ngangkun": "hiccups",
    "wankun": "hiccoughs",
    "warimaji": "yawn",
    "kunji": "sneeze",
}
SUPPORT = {"ngayu", "yundu", "jana", "ngana", "yinya", "yaluy", "yinyay", "nyaji-l"}
DENY_KUKU = {
    "jangkuy", "kankar", "nginja", "numburr", "yanja", "kadil", "kuwimbur", "ngangkurr", "ngingkirr",
    "wulngku", "burri", "kuku", "jawarr", "jalbubun", "ngukal", "nyirray", "yukurr", "yilal",
    "bama", "dingkar", "jalbu", "kaya", "bibiki", "yarraman", "buliki", "ngawa", "karrkay",
    "mayi", "minya", "nuka", "nukan", "nukal", "waju", "wajun", "yurmbi", "warrmba", "warrmban",
    "badi", "badin", "yirrka", "yirrkan", "balka", "balkan", "wuna", "wunan", "dunga", "dungan",
    "bubu", "bayan", "bana", "juku", "kurrun", "jinjajalka", "kurunkal", "madu", "marngkil",
    "marrabal", "milbarakal", "mungari", "wurmbariji", "wuymbariji",
}
DENY_ENGLISH = (
    "chew", "chewing", "clap", "rattle", "rattling", "rustle", "rustling", "whistle", "bark", "barking",
    "song", "sing", "singing", "call", "calling", "shout", "shouting", "cry", "crying", "scream", "screaming",
    "distress", "mourn", "mourning", "death", "dead", "woman", "man", "person", "child", "dog", "pig", "horse",
    "animal", "bird", "motor", "truck", "food", "eat", "eating", "mouth", "teeth", "ear", "body", "sick",
    "sickness", "ill", "illness", "medicine", "story", "country", "place", "tree", "wood", "source", "make",
    "making", "do", "does", "did",
)


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


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


ROWS = [
    row(1, "I hear the cooee.", "Ngayu kawal nyajil.", "ngayu kawal nyaji-l | I cooee hear-NONPAST", "r201_1sg_hear_kawal", ["ngayu", "kawal", "nyaji-l"], "Dictionary kawal 'cooee'; Patz nyaji-l hearing object."),
    row(2, "I hear the halloo.", "Ngayu ngawungkal nyajil.", "ngayu ngawungkal nyaji-l | I halloo hear-NONPAST", "r201_1sg_hear_ngawungkal", ["ngayu", "ngawungkal", "nyaji-l"], "Dictionary ngawungkal 'halloo'; no source-person event."),
    row(3, "I hear the hum.", "Ngayu ngulnkul nyajil.", "ngayu ngulnkul nyaji-l | I hum hear-NONPAST", "r201_1sg_hear_ngulnkul", ["ngayu", "ngulnkul", "nyaji-l"], "Dictionary ngulnkul 'hum'; no tune-making row."),
    row(4, "I hear the grunt.", "Ngayu nyinja nyajil.", "ngayu nyinja nyaji-l | I grunt hear-NONPAST", "r201_1sg_hear_nyinja", ["ngayu", "nyinja", "nyaji-l"], "Dictionary nyinja 'grunt'; pig/source-animal closed."),
    row(5, "I hear the wail.", "Ngayu wungka nyajil.", "ngayu wungka nyaji-l | I wail hear-NONPAST", "r201_1sg_hear_wungka", ["ngayu", "wungka", "nyaji-l"], "Dictionary wungka 'wail'; distress narrative closed."),
    row(6, "I hear the belch.", "Ngayu kandarr nyajil.", "ngayu kandarr nyaji-l | I belch hear-NONPAST", "r201_1sg_hear_kandarr", ["ngayu", "kandarr", "nyaji-l"], "Dictionary kandarr 'belch/burp'; body-state source closed."),
    row(7, "I hear the hiccups.", "Ngayu ngangkun nyajil.", "ngayu ngangkun nyaji-l | I hiccups hear-NONPAST", "r201_1sg_hear_ngangkun", ["ngayu", "ngangkun", "nyaji-l"], "Dictionary ngangkun 'hiccups/hiccoughs'; illness reading closed."),
    row(8, "I hear the hiccoughs.", "Ngayu wankun nyajil.", "ngayu wankun nyaji-l | I hiccoughs hear-NONPAST", "r201_1sg_hear_wankun", ["ngayu", "wankun", "nyaji-l"], "Dictionary wankun 'hiccoughs'; illness reading closed."),
    row(9, "I hear the yawn.", "Ngayu warimaji nyajil.", "ngayu warimaji nyaji-l | I yawn hear-NONPAST", "r201_1sg_hear_warimaji", ["ngayu", "warimaji", "nyaji-l"], "Dictionary warimaji 'yawn'; source-person event closed."),
    row(10, "I hear the sneeze.", "Ngayu kunji nyajil.", "ngayu kunji nyaji-l | I sneeze hear-NONPAST", "r201_1sg_hear_kunji", ["ngayu", "kunji", "nyaji-l"], "Dictionary kunji 'sneeze'; sickness reading closed."),
    row(11, "You hear the cooee there.", "Yundu kawal yinyay nyajil.", "yundu kawal yinyay nyaji-l | you cooee there hear-NONPAST", "r201_2sg_hear_there_kawal", ["yundu", "kawal", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; no source event."),
    row(12, "You hear the halloo there.", "Yundu ngawungkal yinyay nyajil.", "yundu ngawungkal yinyay nyaji-l | you halloo there hear-NONPAST", "r201_2sg_hear_there_ngawungkal", ["yundu", "ngawungkal", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; far-away prose not expanded."),
    row(13, "You hear the hum there.", "Yundu ngulnkul yinyay nyajil.", "yundu ngulnkul yinyay nyaji-l | you hum there hear-NONPAST", "r201_2sg_hear_there_ngulnkul", ["yundu", "ngulnkul", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; no tune-making row."),
    row(14, "You hear the grunt there.", "Yundu nyinja yinyay nyajil.", "yundu nyinja yinyay nyaji-l | you grunt there hear-NONPAST", "r201_2sg_hear_there_nyinja", ["yundu", "nyinja", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; animal source closed."),
    row(15, "You hear the wail there.", "Yundu wungka yinyay nyajil.", "yundu wungka yinyay nyaji-l | you wail there hear-NONPAST", "r201_2sg_hear_there_wungka", ["yundu", "wungka", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; distress narrative closed."),
    row(16, "You hear the belch there.", "Yundu kandarr yinyay nyajil.", "yundu kandarr yinyay nyaji-l | you belch there hear-NONPAST", "r201_2sg_hear_there_kandarr", ["yundu", "kandarr", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; body-state source closed."),
    row(17, "You hear the hiccups there.", "Yundu ngangkun yinyay nyajil.", "yundu ngangkun yinyay nyaji-l | you hiccups there hear-NONPAST", "r201_2sg_hear_there_ngangkun", ["yundu", "ngangkun", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; illness reading closed."),
    row(18, "You hear the hiccoughs there.", "Yundu wankun yinyay nyajil.", "yundu wankun yinyay nyaji-l | you hiccoughs there hear-NONPAST", "r201_2sg_hear_there_wankun", ["yundu", "wankun", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; illness reading closed."),
    row(19, "You hear the yawn there.", "Yundu warimaji yinyay nyajil.", "yundu warimaji yinyay nyaji-l | you yawn there hear-NONPAST", "r201_2sg_hear_there_warimaji", ["yundu", "warimaji", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; source-person event closed."),
    row(20, "You hear the sneeze there.", "Yundu kunji yinyay nyajil.", "yundu kunji yinyay nyaji-l | you sneeze there hear-NONPAST", "r201_2sg_hear_there_kunji", ["yundu", "kunji", "yinyay", "nyaji-l"], "Bare sound noun plus yinyay support; sickness reading closed."),
    row(21, "They heard the cooee there.", "Jana kawal yinyay nyajin.", "jana kawal yinyay nyaji-ny | they cooee there hear-PAST", "r201_3pl_heard_there_kawal", ["jana", "kawal", "yinyay", "nyaji-l"], "Past hearing frame; target remains bare."),
    row(22, "They heard the halloo there.", "Jana ngawungkal yinyay nyajin.", "jana ngawungkal yinyay nyaji-ny | they halloo there hear-PAST", "r201_3pl_heard_there_ngawungkal", ["jana", "ngawungkal", "yinyay", "nyaji-l"], "Past hearing frame; no source-person expansion."),
    row(23, "They heard the hum there.", "Jana ngulnkul yinyay nyajin.", "jana ngulnkul yinyay nyaji-ny | they hum there hear-PAST", "r201_3pl_heard_there_ngulnkul", ["jana", "ngulnkul", "yinyay", "nyaji-l"], "Past hearing frame; no tune-making row."),
    row(24, "They heard the grunt there.", "Jana nyinja yinyay nyajin.", "jana nyinja yinyay nyaji-ny | they grunt there hear-PAST", "r201_3pl_heard_there_nyinja", ["jana", "nyinja", "yinyay", "nyaji-l"], "Past hearing frame; animal source closed."),
    row(25, "They heard the wail there.", "Jana wungka yinyay nyajin.", "jana wungka yinyay nyaji-ny | they wail there hear-PAST", "r201_3pl_heard_there_wungka", ["jana", "wungka", "yinyay", "nyaji-l"], "Past hearing frame; distress narrative closed."),
    row(26, "They heard the belch there.", "Jana kandarr yinyay nyajin.", "jana kandarr yinyay nyaji-ny | they belch there hear-PAST", "r201_3pl_heard_there_kandarr", ["jana", "kandarr", "yinyay", "nyaji-l"], "Past hearing frame; body-state source closed."),
    row(27, "They heard the hiccups there.", "Jana ngangkun yinyay nyajin.", "jana ngangkun yinyay nyaji-ny | they hiccups there hear-PAST", "r201_3pl_heard_there_ngangkun", ["jana", "ngangkun", "yinyay", "nyaji-l"], "Past hearing frame; illness reading closed."),
    row(28, "They heard the hiccoughs there.", "Jana wankun yinyay nyajin.", "jana wankun yinyay nyaji-ny | they hiccoughs there hear-PAST", "r201_3pl_heard_there_wankun", ["jana", "wankun", "yinyay", "nyaji-l"], "Past hearing frame; illness reading closed."),
    row(29, "They heard the yawn there.", "Jana warimaji yinyay nyajin.", "jana warimaji yinyay nyaji-ny | they yawn there hear-PAST", "r201_3pl_heard_there_warimaji", ["jana", "warimaji", "yinyay", "nyaji-l"], "Past hearing frame; source-person event closed."),
    row(30, "They heard the sneeze there.", "Jana kunji yinyay nyajin.", "jana kunji yinyay nyaji-ny | they sneeze there hear-PAST", "r201_3pl_heard_there_kunji", ["jana", "kunji", "yinyay", "nyaji-l"], "Past hearing frame; sickness reading closed."),
    row(31, "We hear the cooee here.", "Ngana kawal yaluy nyajil.", "ngana kawal yaluy nyaji-l | we cooee here hear-NONPAST", "r201_1pl_hear_here_kawal", ["ngana", "kawal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target remains bare."),
    row(32, "We hear the halloo here.", "Ngana ngawungkal yaluy nyajil.", "ngana ngawungkal yaluy nyaji-l | we halloo here hear-NONPAST", "r201_1pl_hear_here_ngawungkal", ["ngana", "ngawungkal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no source-person expansion."),
    row(33, "We hear the hum here.", "Ngana ngulnkul yaluy nyajil.", "ngana ngulnkul yaluy nyaji-l | we hum here hear-NONPAST", "r201_1pl_hear_here_ngulnkul", ["ngana", "ngulnkul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no tune-making row."),
    row(34, "We hear the grunt here.", "Ngana nyinja yaluy nyajil.", "ngana nyinja yaluy nyaji-l | we grunt here hear-NONPAST", "r201_1pl_hear_here_nyinja", ["ngana", "nyinja", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; animal source closed."),
    row(35, "We hear the wail here.", "Ngana wungka yaluy nyajil.", "ngana wungka yaluy nyaji-l | we wail here hear-NONPAST", "r201_1pl_hear_here_wungka", ["ngana", "wungka", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; distress narrative closed."),
    row(36, "We hear the belch here.", "Ngana kandarr yaluy nyajil.", "ngana kandarr yaluy nyaji-l | we belch here hear-NONPAST", "r201_1pl_hear_here_kandarr", ["ngana", "kandarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; body-state source closed."),
    row(37, "We hear the hiccups here.", "Ngana ngangkun yaluy nyajil.", "ngana ngangkun yaluy nyaji-l | we hiccups here hear-NONPAST", "r201_1pl_hear_here_ngangkun", ["ngana", "ngangkun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; illness reading closed."),
    row(38, "We hear the hiccoughs here.", "Ngana wankun yaluy nyajil.", "ngana wankun yaluy nyaji-l | we hiccoughs here hear-NONPAST", "r201_1pl_hear_here_wankun", ["ngana", "wankun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; illness reading closed."),
    row(39, "We hear the yawn here.", "Ngana warimaji yaluy nyajil.", "ngana warimaji yaluy nyaji-l | we yawn here hear-NONPAST", "r201_1pl_hear_here_warimaji", ["ngana", "warimaji", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; source-person event closed."),
    row(40, "We hear the sneeze here.", "Ngana kunji yaluy nyajil.", "ngana kunji yaluy nyaji-l | we sneeze here hear-NONPAST", "r201_1pl_hear_here_kunji", ["ngana", "kunji", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; sickness reading closed."),
    row(41, "I hear that cooee.", "Ngayu yinya kawal nyajil.", "ngayu yinya kawal nyaji-l | I that cooee hear-NONPAST", "r201_1sg_hear_that_kawal", ["ngayu", "yinya", "kawal", "nyaji-l"], "Rule 200 yinya support with a sound noun object."),
    row(42, "I hear that halloo.", "Ngayu yinya ngawungkal nyajil.", "ngayu yinya ngawungkal nyaji-l | I that halloo hear-NONPAST", "r201_1sg_hear_that_ngawungkal", ["ngayu", "yinya", "ngawungkal", "nyaji-l"], "Rule 200 yinya support; no source-person expansion."),
    row(43, "I hear that hum.", "Ngayu yinya ngulnkul nyajil.", "ngayu yinya ngulnkul nyaji-l | I that hum hear-NONPAST", "r201_1sg_hear_that_ngulnkul", ["ngayu", "yinya", "ngulnkul", "nyaji-l"], "Rule 200 yinya support; no tune-making row."),
    row(44, "I hear that grunt.", "Ngayu yinya nyinja nyajil.", "ngayu yinya nyinja nyaji-l | I that grunt hear-NONPAST", "r201_1sg_hear_that_nyinja", ["ngayu", "yinya", "nyinja", "nyaji-l"], "Rule 200 yinya support; animal source closed."),
    row(45, "I hear that wail.", "Ngayu yinya wungka nyajil.", "ngayu yinya wungka nyaji-l | I that wail hear-NONPAST", "r201_1sg_hear_that_wungka", ["ngayu", "yinya", "wungka", "nyaji-l"], "Rule 200 yinya support; distress narrative closed."),
    row(46, "I hear that belch.", "Ngayu yinya kandarr nyajil.", "ngayu yinya kandarr nyaji-l | I that belch hear-NONPAST", "r201_1sg_hear_that_kandarr", ["ngayu", "yinya", "kandarr", "nyaji-l"], "Rule 200 yinya support; body-state source closed."),
    row(47, "I hear that hiccups.", "Ngayu yinya ngangkun nyajil.", "ngayu yinya ngangkun nyaji-l | I that hiccups hear-NONPAST", "r201_1sg_hear_that_ngangkun", ["ngayu", "yinya", "ngangkun", "nyaji-l"], "Rule 200 yinya support; illness reading closed."),
    row(48, "I hear that hiccoughs.", "Ngayu yinya wankun nyajil.", "ngayu yinya wankun nyaji-l | I that hiccoughs hear-NONPAST", "r201_1sg_hear_that_wankun", ["ngayu", "yinya", "wankun", "nyaji-l"], "Rule 200 yinya support; illness reading closed."),
    row(49, "I hear that yawn.", "Ngayu yinya warimaji nyajil.", "ngayu yinya warimaji nyaji-l | I that yawn hear-NONPAST", "r201_1sg_hear_that_warimaji", ["ngayu", "yinya", "warimaji", "nyaji-l"], "Rule 200 yinya support; source-person event closed."),
    row(50, "I hear that sneeze.", "Ngayu yinya kunji nyajil.", "ngayu yinya kunji nyaji-l | I that sneeze hear-NONPAST", "r201_1sg_hear_that_kunji", ["ngayu", "yinya", "kunji", "nyaji-l"], "Rule 200 yinya support; sickness reading closed."),
]


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


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


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


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"{LABEL}: expected 50 rows, found {len(ROWS)}")
    seen_ku: set[str] = set()
    for expected, row_data in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row_data
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        if seq != expected:
            issues.append(f"{label}: sequence mismatch; expected {expected}")
        if not english[:1].isupper() or english[-1:] not in ".!?":
            issues.append(f"{label}: English punctuation/capitalization failure")
        if " | " not in analysis:
            issues.append(f"{label}: analysis missing gloss separator")
        if not frame.startswith("r201_"):
            issues.append(f"{label}: Rule 201 frame must start with r201_")
        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 201")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied previous-field/source/event 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 201 sound target, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected 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 support == "nyaji-l":
                continue
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if "nyaji-l" not in words:
            issues.append(f"{label}: Rule 201 rows require nyaji-l support")
        if 1 <= seq <= 10 and (not low.startswith("ngayu ") or not low.endswith(" nyajil.") or has_token(low, "yaluy") or has_token(low, "yinyay") or has_token(low, "yinya")):
            issues.append(f"{label}: rows 1-10 require Ngayu TARGET nyajil")
        if 11 <= seq <= 20 and (not low.startswith("yundu ") or not has_token(low, "yinyay") or has_token(low, "yaluy") or has_token(low, "yinya") or not low.endswith(" nyajil.")):
            issues.append(f"{label}: rows 11-20 require Yundu TARGET yinyay nyajil")
        if 21 <= seq <= 30 and (not low.startswith("jana ") or not has_token(low, "yinyay") or has_token(low, "yaluy") or has_token(low, "yinya") or not low.endswith(" nyajin.")):
            issues.append(f"{label}: rows 21-30 require Jana TARGET yinyay nyajin")
        if 31 <= seq <= 40 and (not low.startswith("ngana ") or not has_token(low, "yaluy") or has_token(low, "yinyay") or has_token(low, "yinya") or not low.endswith(" nyajil.")):
            issues.append(f"{label}: rows 31-40 require Ngana TARGET yaluy nyajil")
        if 41 <= seq <= 50 and (not low.startswith("ngayu yinya ") or has_token(low, "yaluy") or has_token(low, "yinyay") or not low.endswith(" nyajil.")):
            issues.append(f"{label}: rows 41-50 require Ngayu yinya TARGET nyajil")
        if "nyajin" in low and "hear-PAST" not in analysis:
            issues.append(f"{label}: nyajin must be glossed as hear-PAST")
        if "nyajil" in low and "hear-NONPAST" not in analysis:
            issues.append(f"{label}: nyajil must be glossed as hear-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied source/event/body-state 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 201 draft: audible-sound reference lexical expansion after Rule 200",
                "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 201 source pass selected ten unused dictionary-backed audible-sound/body-sound nouns: kawal, ngawungkal, ngulnkul, nyinja, wungka, kandarr, ngangkun, wankun, warimaji, and kunji. Patz example 109 and dictionary nyajil support nyaji-l as hear/perceive; Patz 4.2.1 supports pronoun experiencer A in sensory-perception clauses.",
        command="dictionary.yaml exact readback; grammar.md nyaji-l hearing examples; sqlite corpus frequency check and duplicate preflight",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="lexical-scope",
        actor="claude-main",
        detail="Rule 201 is an audible-sound lexical expansion. It admits bare sound nouns only as objects of nyaji-l in the hear/heard sense and excludes sound-making events, source persons/animals, food/eating, illness, distress narratives, body-part possession, target morphology, and previous sound-batch heads.",
        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 audible-sound reference surfaces returned no accepted/revised/under_review collisions.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_243.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guard passed: exactly 50 unique surfaces; exactly one sound target per row; all target heads bare; no loans; no previous sound-batch or tree-reference tokens; no denied source/event/body-state English; and correct hear-NONPAST/hear-PAST frame distribution.",
        command="python3 batch_scripts/bank_243.py pre-bank scan",
        artifact_path="batch_scripts/bank_243.py",
        created_at=NOW,
    )

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

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


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