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

TARGET_HEADS = {
    "bala": "sugar glider",
    "darrba": "grass wallaby",
    "jarrabina": "tree kangaroo",
    "jayju": "kangaroo rat",
    "jungarr": "marsupial native cat",
    "kukur": "rat",
    "mali": "small bat",
    "murramu": "dingo",
    "ngumbi": "bandicoot",
    "yawa": "possum",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "bimbarrbay", "durrkin", "jibul", "kirbaji", "jumar", "murrumu", "nyarrkali",
    "wambiji", "waykal", "yalmburrajaka", "biki", "bikibiki", "biwuy", "buji",
    "danda", "kadar", "kambi", "kaya", "kaya-kaya", "kulngu", "mayarriji",
    "murral", "ngamu-murramu", "ngangkin", "yarraman", "baban", "bububay",
    "ngalkun", "walkan", "barrbal", "jalkay", "janbal", "jijirr", "kurrubal",
    "murraja",
}
DENY_ENGLISH = (
    "hunt", "hunting", "hunter", "catch", "caught", "catching", "trap", "trapped",
    "kill", "killed", "bite", "biting", "attack", "spear", "speared", "food", "edible",
    "eat", "eating", "ate", "meat", "cook", "cooked", "skin", "fur", "tail", "claw",
    "body-part", "bone", "fat", "habitat", "ecology", "tree-climbing", "climb",
    "branch", "hollow", "cave", "story", "story-site", "place-name", "totem", "moiety",
    "ceremony", "water", "river", "sea", "ocean", "iron", "clothing", "source material",
    "loan", "introduced", "pig", "horse", "dog", "domestic cat", "cat loan", "cat-loan",
    "skinny", "weak", "full", "door", "front", "colour", "color", "plural", "many",
)


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 sugar glider is here.", "Bala yaluy.", "bala yaluy | sugar.glider here", "r219_mammal_ref_here_bala", ["bala", "yaluy"], "Dictionary bala noun 'sugar glider'; homonymous skinny adjective fenced off. Patz section 3.1 nouns include fauna; section 3.7 yaluy 'here'."),
    row(2, "The grass wallaby is here.", "Darrba yaluy.", "darrba yaluy | grass.wallaby here", "r219_mammal_ref_here_darrba", ["darrba", "yaluy"], "Dictionary darrba noun 'grass wallaby'. Patz section 3.7 yaluy."),
    row(3, "The tree kangaroo is here.", "Jarrabina yaluy.", "jarrabina yaluy | tree.kangaroo here", "r219_mammal_ref_here_jarrabina", ["jarrabina", "yaluy"], "Dictionary jarrabina noun 'tree kangaroo' from definition 'tree-climbing kangaroo'; habitat/event readings fenced off. Patz section 3.7 yaluy."),
    row(4, "The kangaroo rat is here.", "Jayju yaluy.", "jayju yaluy | kangaroo.rat here", "r219_mammal_ref_here_jayju", ["jayju", "yaluy"], "Dictionary jayju noun 'kangaroo rat'. Patz section 3.7 yaluy."),
    row(5, "The marsupial native cat is here.", "Jungarr yaluy.", "jungarr yaluy | marsupial.native.cat here", "r219_mammal_ref_here_jungarr", ["jungarr", "yaluy"], "Dictionary jungarr noun 'marsupial native cat' with quoll commentary; introduced-cat drift fenced off. Patz section 3.7 yaluy."),
    row(6, "The rat is here.", "Kukur yaluy.", "kukur yaluy | rat here", "r219_mammal_ref_here_kukur", ["kukur", "yaluy"], "Dictionary kukur noun 'rat'. Patz section 3.7 yaluy."),
    row(7, "The small bat is here.", "Mali yaluy.", "mali yaluy | small.bat here", "r219_mammal_ref_here_mali", ["mali", "yaluy"], "Dictionary mali noun 'species of small bat'. Patz section 3.7 yaluy."),
    row(8, "The dingo is here.", "Murramu yaluy.", "murramu yaluy | dingo here", "r219_mammal_ref_here_murramu", ["murramu", "yaluy"], "Dictionary murramu noun 'dingo'; dog/loan and attack/event drift fenced off. Patz section 3.7 yaluy."),
    row(9, "The bandicoot is here.", "Ngumbi yaluy.", "ngumbi yaluy | bandicoot here", "r219_mammal_ref_here_ngumbi", ["ngumbi", "yaluy"], "Dictionary ngumbi noun 'little spotted bandicoot'; production label narrowed to bandicoot. Patz section 3.7 yaluy."),
    row(10, "The possum is here.", "Yawa yaluy.", "yawa yaluy | possum here", "r219_mammal_ref_here_yawa", ["yawa", "yaluy"], "Dictionary yawa noun 'possum'. Patz section 3.7 yaluy."),
    row(11, "The sugar glider is there.", "Bala yinyay.", "bala yinyay | sugar.glider there", "r219_mammal_ref_there_bala", ["bala", "yinyay"], "Dictionary bala noun 'sugar glider'; Patz section 3.7 yinyay 'there'."),
    row(12, "The grass wallaby is there.", "Darrba yinyay.", "darrba yinyay | grass.wallaby there", "r219_mammal_ref_there_darrba", ["darrba", "yinyay"], "Dictionary darrba noun 'grass wallaby'; Patz section 3.7 yinyay."),
    row(13, "The tree kangaroo is there.", "Jarrabina yinyay.", "jarrabina yinyay | tree.kangaroo there", "r219_mammal_ref_there_jarrabina", ["jarrabina", "yinyay"], "Dictionary jarrabina noun 'tree kangaroo'; Patz section 3.7 yinyay."),
    row(14, "The kangaroo rat is there.", "Jayju yinyay.", "jayju yinyay | kangaroo.rat there", "r219_mammal_ref_there_jayju", ["jayju", "yinyay"], "Dictionary jayju noun 'kangaroo rat'; Patz section 3.7 yinyay."),
    row(15, "The marsupial native cat is there.", "Jungarr yinyay.", "jungarr yinyay | marsupial.native.cat there", "r219_mammal_ref_there_jungarr", ["jungarr", "yinyay"], "Dictionary jungarr noun 'marsupial native cat'; Patz section 3.7 yinyay."),
    row(16, "The rat is there.", "Kukur yinyay.", "kukur yinyay | rat there", "r219_mammal_ref_there_kukur", ["kukur", "yinyay"], "Dictionary kukur noun 'rat'; Patz section 3.7 yinyay."),
    row(17, "The small bat is there.", "Mali yinyay.", "mali yinyay | small.bat there", "r219_mammal_ref_there_mali", ["mali", "yinyay"], "Dictionary mali noun 'small bat'; Patz section 3.7 yinyay."),
    row(18, "The dingo is there.", "Murramu yinyay.", "murramu yinyay | dingo there", "r219_mammal_ref_there_murramu", ["murramu", "yinyay"], "Dictionary murramu noun 'dingo'; Patz section 3.7 yinyay."),
    row(19, "The bandicoot is there.", "Ngumbi yinyay.", "ngumbi yinyay | bandicoot there", "r219_mammal_ref_there_ngumbi", ["ngumbi", "yinyay"], "Dictionary ngumbi noun 'bandicoot'; Patz section 3.7 yinyay."),
    row(20, "The possum is there.", "Yawa yinyay.", "yawa yinyay | possum there", "r219_mammal_ref_there_yawa", ["yawa", "yinyay"], "Dictionary yawa noun 'possum'; Patz section 3.7 yinyay."),
    row(21, "That sugar glider is there.", "Yinya bala yinyay.", "yinya bala yinyay | that sugar.glider there", "r219_that_mammal_ref_there_bala", ["yinya", "bala", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dictionary bala noun 'sugar glider'."),
    row(22, "That grass wallaby is there.", "Yinya darrba yinyay.", "yinya darrba yinyay | that grass.wallaby there", "r219_that_mammal_ref_there_darrba", ["yinya", "darrba", "yinyay"], "Patz section 3.7 yinya with noun; dictionary darrba noun 'grass wallaby'."),
    row(23, "That tree kangaroo is there.", "Yinya jarrabina yinyay.", "yinya jarrabina yinyay | that tree.kangaroo there", "r219_that_mammal_ref_there_jarrabina", ["yinya", "jarrabina", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jarrabina noun 'tree kangaroo'."),
    row(24, "That kangaroo rat is there.", "Yinya jayju yinyay.", "yinya jayju yinyay | that kangaroo.rat there", "r219_that_mammal_ref_there_jayju", ["yinya", "jayju", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jayju noun 'kangaroo rat'."),
    row(25, "That marsupial native cat is there.", "Yinya jungarr yinyay.", "yinya jungarr yinyay | that marsupial.native.cat there", "r219_that_mammal_ref_there_jungarr", ["yinya", "jungarr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jungarr noun 'marsupial native cat'."),
    row(26, "That rat is there.", "Yinya kukur yinyay.", "yinya kukur yinyay | that rat there", "r219_that_mammal_ref_there_kukur", ["yinya", "kukur", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kukur noun 'rat'."),
    row(27, "That small bat is there.", "Yinya mali yinyay.", "yinya mali yinyay | that small.bat there", "r219_that_mammal_ref_there_mali", ["yinya", "mali", "yinyay"], "Patz section 3.7 yinya with noun; dictionary mali noun 'small bat'."),
    row(28, "That dingo is there.", "Yinya murramu yinyay.", "yinya murramu yinyay | that dingo there", "r219_that_mammal_ref_there_murramu", ["yinya", "murramu", "yinyay"], "Patz section 3.7 yinya with noun; dictionary murramu noun 'dingo'."),
    row(29, "That bandicoot is there.", "Yinya ngumbi yinyay.", "yinya ngumbi yinyay | that bandicoot there", "r219_that_mammal_ref_there_ngumbi", ["yinya", "ngumbi", "yinyay"], "Patz section 3.7 yinya with noun; dictionary ngumbi noun 'bandicoot'."),
    row(30, "That possum is there.", "Yinya yawa yinyay.", "yinya yawa yinyay | that possum there", "r219_that_mammal_ref_there_yawa", ["yinya", "yawa", "yinyay"], "Patz section 3.7 yinya with noun; dictionary yawa noun 'possum'."),
    row(31, "That sugar glider is there.", "Bala yinya yinyay.", "bala yinya yinyay | that sugar.glider there", "r219_mammal_that_there_bala", ["bala", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bala noun 'sugar glider'."),
    row(32, "That grass wallaby is there.", "Darrba yinya yinyay.", "darrba yinya yinyay | that grass.wallaby there", "r219_mammal_that_there_darrba", ["darrba", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary darrba noun 'grass wallaby'."),
    row(33, "That tree kangaroo is there.", "Jarrabina yinya yinyay.", "jarrabina yinya yinyay | that tree.kangaroo there", "r219_mammal_that_there_jarrabina", ["jarrabina", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jarrabina noun 'tree kangaroo'."),
    row(34, "That kangaroo rat is there.", "Jayju yinya yinyay.", "jayju yinya yinyay | that kangaroo.rat there", "r219_mammal_that_there_jayju", ["jayju", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jayju noun 'kangaroo rat'."),
    row(35, "That marsupial native cat is there.", "Jungarr yinya yinyay.", "jungarr yinya yinyay | that marsupial.native.cat there", "r219_mammal_that_there_jungarr", ["jungarr", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jungarr noun 'marsupial native cat'."),
    row(36, "That rat is there.", "Kukur yinya yinyay.", "kukur yinya yinyay | that rat there", "r219_mammal_that_there_kukur", ["kukur", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary kukur noun 'rat'."),
    row(37, "That small bat is there.", "Mali yinya yinyay.", "mali yinya yinyay | that small.bat there", "r219_mammal_that_there_mali", ["mali", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary mali noun 'small bat'."),
    row(38, "That dingo is there.", "Murramu yinya yinyay.", "murramu yinya yinyay | that dingo there", "r219_mammal_that_there_murramu", ["murramu", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary murramu noun 'dingo'."),
    row(39, "That bandicoot is there.", "Ngumbi yinya yinyay.", "ngumbi yinya yinyay | that bandicoot there", "r219_mammal_that_there_ngumbi", ["ngumbi", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary ngumbi noun 'bandicoot'."),
    row(40, "That possum is there.", "Yawa yinya yinyay.", "yawa yinya yinyay | that possum there", "r219_mammal_that_there_yawa", ["yawa", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary yawa noun 'possum'."),
    row(41, "That sugar glider is here.", "Yinya bala yaluy.", "yinya bala yaluy | that sugar.glider here", "r219_that_mammal_ref_here_bala", ["yinya", "bala", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bala noun 'sugar glider'; yaluy 'here'."),
    row(42, "That grass wallaby is here.", "Yinya darrba yaluy.", "yinya darrba yaluy | that grass.wallaby here", "r219_that_mammal_ref_here_darrba", ["yinya", "darrba", "yaluy"], "Patz section 3.7 yinya with noun; dictionary darrba noun 'grass wallaby'; yaluy 'here'."),
    row(43, "That tree kangaroo is here.", "Yinya jarrabina yaluy.", "yinya jarrabina yaluy | that tree.kangaroo here", "r219_that_mammal_ref_here_jarrabina", ["yinya", "jarrabina", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jarrabina noun 'tree kangaroo'; yaluy 'here'."),
    row(44, "That kangaroo rat is here.", "Yinya jayju yaluy.", "yinya jayju yaluy | that kangaroo.rat here", "r219_that_mammal_ref_here_jayju", ["yinya", "jayju", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jayju noun 'kangaroo rat'; yaluy 'here'."),
    row(45, "That marsupial native cat is here.", "Yinya jungarr yaluy.", "yinya jungarr yaluy | that marsupial.native.cat here", "r219_that_mammal_ref_here_jungarr", ["yinya", "jungarr", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jungarr noun 'marsupial native cat'; yaluy 'here'."),
    row(46, "That rat is here.", "Yinya kukur yaluy.", "yinya kukur yaluy | that rat here", "r219_that_mammal_ref_here_kukur", ["yinya", "kukur", "yaluy"], "Patz section 3.7 yinya with noun; dictionary kukur noun 'rat'; yaluy 'here'."),
    row(47, "That small bat is here.", "Yinya mali yaluy.", "yinya mali yaluy | that small.bat here", "r219_that_mammal_ref_here_mali", ["yinya", "mali", "yaluy"], "Patz section 3.7 yinya with noun; dictionary mali noun 'small bat'; yaluy 'here'."),
    row(48, "That dingo is here.", "Yinya murramu yaluy.", "yinya murramu yaluy | that dingo here", "r219_that_mammal_ref_here_murramu", ["yinya", "murramu", "yaluy"], "Patz section 3.7 yinya with noun; dictionary murramu noun 'dingo'; yaluy 'here'."),
    row(49, "That bandicoot is here.", "Yinya ngumbi yaluy.", "yinya ngumbi yaluy | that bandicoot here", "r219_that_mammal_ref_here_ngumbi", ["yinya", "ngumbi", "yaluy"], "Patz section 3.7 yinya with noun; dictionary ngumbi noun 'bandicoot'; yaluy 'here'."),
    row(50, "That possum is here.", "Yinya yawa yaluy.", "yinya yawa yaluy | that possum here", "r219_that_mammal_ref_here_yawa", ["yinya", "yawa", "yaluy"], "Patz section 3.7 yinya with noun; dictionary yawa noun 'possum'; 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.strip())}\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("r219_"):
            issues.append(f"{label}: Rule 219 frame must start with r219_")
        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 219")
        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 219 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.") or len(low.split()) != 2):
            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.") or len(low.split()) != 2):
            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.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 21-30 require Yinya TARGET yinyay")
        if 31 <= seq <= 40 and (not has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 3 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.") or len(low.split()) != 3):
            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 mammal use/habitat/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 219 draft: second mammal-reference lexical expansion after Rule 218",
                "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, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, "claude", NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence 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()
    under_review = db.execute(
        "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'",
        (batch_id,),
    ).fetchone()[0]

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail=(
            "Checked Patz section 3.1 noun/fauna basis, Patz section 3.7 yinya/yaluy/yinyay support, earlier Rule 177-178 mammal rows, "
            "and dictionary entries for bala, darrba, jarrabina, jayju, jungarr, kukur, mali, murramu, ngumbi, and yawa. "
            "Admitted only selected bare mammal-reference labels."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail=(
            "Selected a second mammal-reference field after excluding exact Rule 177-178 deictic surfaces, grammar-added pig loan, introduced horse terms, "
            "plural/reduplicated forms, empty-gloss entries, strong homograph pressure where avoidable, and all hunting, food, habitat, body-part, source-material, colour, and event semantics."
        ),
        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 219 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="python3 batch_scripts/bank_261.py cross-corpus duplicate scan",
        artifact_path="batch_scripts/bank_261.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail=(
            "bank_261.py static guards passed: 50 explicit hand-authored rows, exactly one mammal-reference target noun per row, no loans, "
            "no target morphology, no mammal-use/habitat/event/polysemy English, and only the five sourced deictic frame bands."
        ),
        artifact_path="batch_scripts/bank_261.py",
        created_at=NOW,
    )
    db.commit()
    print(
        f"banked {LABEL}: rows={len(ROWS)}, under_review={under_review}, "
        f"verified_before_close={verified_before}, words_before={words_before or 0}"
    )
    return 0


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