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

TARGET_HEADS = {
    "baybu": "pipe",
    "binjin": "petrol",
    "biyin": "safety pin",
    "dakilji": "cup",
    "dingkil-dingkil": "bell",
    "jamu": "cork",
    "julnji": "tar",
    "kilaja": "mirror",
    "mudaka": "motor car",
    "wuba": "red ochre",
}
LOAN_HEADS = {"baybu", "binjin", "biyin", "dingkil-dingkil", "kilaja", "mudaka"}
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", "baya", "kubu",
    "ngunjil", "wula", "bana", "baral", "murru", "bubu", "juku", "kalka", "wawu",
}
DENY_ENGLISH = (
    "use", "uses", "used", "using", "make", "made", "making", "manufacture", "repair", "fix",
    "smoke", "smoking", "blow", "fuel", "burn", "burning", "fire", "light", "lighting", "drive",
    "driving", "ride", "riding", "travel", "road", "vehicle", "carrying", "carry", "fill", "filling",
    "drink", "drinking", "ring", "ringing", "sound", "hear", "ceremony", "warning", "look", "looking",
    "reflect", "reflection", "cut", "glass-source", "bottle", "stopper", "float", "tree", "spear",
    "adhesive", "heat", "heated", "petrol for", "clothing", "fasten", "fastening", "pierce", "piercing",
    "paint", "painting", "pigment", "body-marking", "grind", "grinding", "mix", "mixing",
    "own", "belongs", "possession",
)


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,
    loans: list[str] | None = None,
) -> tuple:
    return (seq, english, kuku, analysis, frame, 2, js(words), js(loans or []), evidence, "0.86")


ROWS = [
    row(1, "The pipe is here.", "Baybu yaluy.", "baybu yaluy | pipe here", "r209_deictic_here_baybu", ["baybu", "yaluy"], "Dictionary baybu noun 'pipe'; loanword source recorded; Patz section 3.7 yaluy 'here'.", ["baybu"]),
    row(2, "The petrol is here.", "Binjin yaluy.", "binjin yaluy | petrol here", "r209_deictic_here_binjin", ["binjin", "yaluy"], "Dictionary binjin noun 'petrol, fuel'; Patz section 2.3 loan attestation; Patz section 3.7 yaluy.", ["binjin"]),
    row(3, "The safety pin is here.", "Biyin yaluy.", "biyin yaluy | safety.pin here", "r209_deictic_here_biyin", ["biyin", "yaluy"], "Dictionary biyin noun '(safety) pin'; Patz section 2.3 loan attestation; Patz section 3.7 yaluy.", ["biyin"]),
    row(4, "The cup is here.", "Dakilji yaluy.", "dakilji yaluy | cup here", "r209_deictic_here_dakilji", ["dakilji", "yaluy"], "Dictionary dakilji noun 'cup'; Patz section 3.7 yaluy 'here'."),
    row(5, "The bell is here.", "Dingkil-dingkil yaluy.", "dingkil-dingkil yaluy | bell here", "r209_deictic_here_dingkil_dingkil", ["dingkil-dingkil", "yaluy"], "Dictionary dingkil-dingkil noun 'bell'; loan noted; Patz section 3.7 yaluy.", ["dingkil-dingkil"]),
    row(6, "The red ochre is here.", "Wuba yaluy.", "wuba yaluy | red.ochre here", "r209_deictic_here_wuba", ["wuba", "yaluy"], "Dictionary wuba noun 'red ochre'; pigment-use prose kept closed; Patz section 3.7 yaluy."),
    row(7, "The cork is here.", "Jamu yaluy.", "jamu yaluy | cork here", "r209_deictic_here_jamu", ["jamu", "yaluy"], "Dictionary jamu noun 'cork from bottle'; selected cork reference only; Patz section 3.7 yaluy."),
    row(8, "The tar is here.", "Julnji yaluy.", "julnji yaluy | tar here", "r209_deictic_here_julnji", ["julnji", "yaluy"], "Dictionary julnji noun 'tar'; source/use prose kept closed; Patz section 3.7 yaluy."),
    row(9, "The mirror is here.", "Kilaja yaluy.", "kilaja yaluy | mirror here", "r209_deictic_here_kilaja", ["kilaja", "yaluy"], "Dictionary kilaja noun 'mirror'; loan from glass noted; Patz section 3.7 yaluy.", ["kilaja"]),
    row(10, "The motor car is here.", "Mudaka yaluy.", "mudaka yaluy | motor.car here", "r209_deictic_here_mudaka", ["mudaka", "yaluy"], "Dictionary mudaka noun 'motor car'; English loan noted; Patz section 3.7 yaluy.", ["mudaka"]),
    row(11, "The pipe is there.", "Baybu yinyay.", "baybu yinyay | pipe there", "r209_deictic_there_baybu", ["baybu", "yinyay"], "Dictionary baybu noun 'pipe'; Patz section 3.7 yinyay 'there'.", ["baybu"]),
    row(12, "The petrol is there.", "Binjin yinyay.", "binjin yinyay | petrol there", "r209_deictic_there_binjin", ["binjin", "yinyay"], "Dictionary binjin noun 'petrol, fuel'; Patz section 3.7 yinyay.", ["binjin"]),
    row(13, "The safety pin is there.", "Biyin yinyay.", "biyin yinyay | safety.pin there", "r209_deictic_there_biyin", ["biyin", "yinyay"], "Dictionary biyin noun '(safety) pin'; Patz section 3.7 yinyay.", ["biyin"]),
    row(14, "The cup is there.", "Dakilji yinyay.", "dakilji yinyay | cup there", "r209_deictic_there_dakilji", ["dakilji", "yinyay"], "Dictionary dakilji noun 'cup'; Patz section 3.7 yinyay."),
    row(15, "The bell is there.", "Dingkil-dingkil yinyay.", "dingkil-dingkil yinyay | bell there", "r209_deictic_there_dingkil_dingkil", ["dingkil-dingkil", "yinyay"], "Dictionary dingkil-dingkil noun 'bell'; Patz section 3.7 yinyay.", ["dingkil-dingkil"]),
    row(16, "The red ochre is there.", "Wuba yinyay.", "wuba yinyay | red.ochre there", "r209_deictic_there_wuba", ["wuba", "yinyay"], "Dictionary wuba noun 'red ochre'; Patz section 3.7 yinyay."),
    row(17, "The cork is there.", "Jamu yinyay.", "jamu yinyay | cork there", "r209_deictic_there_jamu", ["jamu", "yinyay"], "Dictionary jamu noun 'cork from bottle'; selected cork reference only; Patz section 3.7 yinyay."),
    row(18, "The tar is there.", "Julnji yinyay.", "julnji yinyay | tar there", "r209_deictic_there_julnji", ["julnji", "yinyay"], "Dictionary julnji noun 'tar'; source/use prose kept closed; Patz section 3.7 yinyay."),
    row(19, "The mirror is there.", "Kilaja yinyay.", "kilaja yinyay | mirror there", "r209_deictic_there_kilaja", ["kilaja", "yinyay"], "Dictionary kilaja noun 'mirror'; Patz section 3.7 yinyay.", ["kilaja"]),
    row(20, "The motor car is there.", "Mudaka yinyay.", "mudaka yinyay | motor.car there", "r209_deictic_there_mudaka", ["mudaka", "yinyay"], "Dictionary mudaka noun 'motor car'; Patz section 3.7 yinyay.", ["mudaka"]),
    row(21, "That pipe is there.", "Yinya baybu yinyay.", "yinya baybu yinyay | that pipe there", "r209_initial_that_there_baybu", ["yinya", "baybu", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; baybu pipe; yinyay there.", ["baybu"]),
    row(22, "That petrol is there.", "Yinya binjin yinyay.", "yinya binjin yinyay | that petrol there", "r209_initial_that_there_binjin", ["yinya", "binjin", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; binjin petrol; yinyay there.", ["binjin"]),
    row(23, "That safety pin is there.", "Yinya biyin yinyay.", "yinya biyin yinyay | that safety.pin there", "r209_initial_that_there_biyin", ["yinya", "biyin", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; biyin safety pin; yinyay there.", ["biyin"]),
    row(24, "That cup is there.", "Yinya dakilji yinyay.", "yinya dakilji yinyay | that cup there", "r209_initial_that_there_dakilji", ["yinya", "dakilji", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dakilji cup; yinyay there."),
    row(25, "That bell is there.", "Yinya dingkil-dingkil yinyay.", "yinya dingkil-dingkil yinyay | that bell there", "r209_initial_that_there_dingkil_dingkil", ["yinya", "dingkil-dingkil", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dingkil-dingkil bell; yinyay there.", ["dingkil-dingkil"]),
    row(26, "That red ochre is there.", "Yinya wuba yinyay.", "yinya wuba yinyay | that red.ochre there", "r209_initial_that_there_wuba", ["yinya", "wuba", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; wuba red ochre; yinyay there."),
    row(27, "That cork is there.", "Yinya jamu yinyay.", "yinya jamu yinyay | that cork there", "r209_initial_that_there_jamu", ["yinya", "jamu", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; jamu cork; yinyay there."),
    row(28, "That tar is there.", "Yinya julnji yinyay.", "yinya julnji yinyay | that tar there", "r209_initial_that_there_julnji", ["yinya", "julnji", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; julnji tar; yinyay there."),
    row(29, "That mirror is there.", "Yinya kilaja yinyay.", "yinya kilaja yinyay | that mirror there", "r209_initial_that_there_kilaja", ["yinya", "kilaja", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; kilaja mirror; yinyay there.", ["kilaja"]),
    row(30, "That motor car is there.", "Yinya mudaka yinyay.", "yinya mudaka yinyay | that motor.car there", "r209_initial_that_there_mudaka", ["yinya", "mudaka", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; mudaka motor car; yinyay there.", ["mudaka"]),
    row(31, "That pipe is there.", "Baybu yinya yinyay.", "baybu yinya yinyay | pipe that there", "r209_postposed_that_there_baybu", ["baybu", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; baybu pipe; yinyay there.", ["baybu"]),
    row(32, "That petrol is there.", "Binjin yinya yinyay.", "binjin yinya yinyay | petrol that there", "r209_postposed_that_there_binjin", ["binjin", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; binjin petrol; yinyay there.", ["binjin"]),
    row(33, "That safety pin is there.", "Biyin yinya yinyay.", "biyin yinya yinyay | safety.pin that there", "r209_postposed_that_there_biyin", ["biyin", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; biyin safety pin; yinyay there.", ["biyin"]),
    row(34, "That cup is there.", "Dakilji yinya yinyay.", "dakilji yinya yinyay | cup that there", "r209_postposed_that_there_dakilji", ["dakilji", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; dakilji cup; yinyay there."),
    row(35, "That bell is there.", "Dingkil-dingkil yinya yinyay.", "dingkil-dingkil yinya yinyay | bell that there", "r209_postposed_that_there_dingkil_dingkil", ["dingkil-dingkil", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; dingkil-dingkil bell; yinyay there.", ["dingkil-dingkil"]),
    row(36, "That red ochre is there.", "Wuba yinya yinyay.", "wuba yinya yinyay | red.ochre that there", "r209_postposed_that_there_wuba", ["wuba", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; wuba red ochre; yinyay there."),
    row(37, "That cork is there.", "Jamu yinya yinyay.", "jamu yinya yinyay | cork that there", "r209_postposed_that_there_jamu", ["jamu", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; jamu cork; yinyay there."),
    row(38, "That tar is there.", "Julnji yinya yinyay.", "julnji yinya yinyay | tar that there", "r209_postposed_that_there_julnji", ["julnji", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; julnji tar; yinyay there."),
    row(39, "That mirror is there.", "Kilaja yinya yinyay.", "kilaja yinya yinyay | mirror that there", "r209_postposed_that_there_kilaja", ["kilaja", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; kilaja mirror; yinyay there.", ["kilaja"]),
    row(40, "That motor car is there.", "Mudaka yinya yinyay.", "mudaka yinya yinyay | motor.car that there", "r209_postposed_that_there_mudaka", ["mudaka", "yinya", "yinyay"], "Patz section 3.7 permits yinya after a noun; mudaka motor car; yinyay there.", ["mudaka"]),
    row(41, "That pipe is here.", "Yinya baybu yaluy.", "yinya baybu yaluy | that pipe here", "r209_initial_that_here_baybu", ["yinya", "baybu", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; baybu pipe; yaluy here.", ["baybu"]),
    row(42, "That petrol is here.", "Yinya binjin yaluy.", "yinya binjin yaluy | that petrol here", "r209_initial_that_here_binjin", ["yinya", "binjin", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; binjin petrol; yaluy here.", ["binjin"]),
    row(43, "That safety pin is here.", "Yinya biyin yaluy.", "yinya biyin yaluy | that safety.pin here", "r209_initial_that_here_biyin", ["yinya", "biyin", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; biyin safety pin; yaluy here.", ["biyin"]),
    row(44, "That cup is here.", "Yinya dakilji yaluy.", "yinya dakilji yaluy | that cup here", "r209_initial_that_here_dakilji", ["yinya", "dakilji", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; dakilji cup; yaluy here."),
    row(45, "That bell is here.", "Yinya dingkil-dingkil yaluy.", "yinya dingkil-dingkil yaluy | that bell here", "r209_initial_that_here_dingkil_dingkil", ["yinya", "dingkil-dingkil", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; dingkil-dingkil bell; yaluy here.", ["dingkil-dingkil"]),
    row(46, "That red ochre is here.", "Yinya wuba yaluy.", "yinya wuba yaluy | that red.ochre here", "r209_initial_that_here_wuba", ["yinya", "wuba", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; wuba red ochre; yaluy here."),
    row(47, "That cork is here.", "Yinya jamu yaluy.", "yinya jamu yaluy | that cork here", "r209_initial_that_here_jamu", ["yinya", "jamu", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; jamu cork; yaluy here."),
    row(48, "That tar is here.", "Yinya julnji yaluy.", "yinya julnji yaluy | that tar here", "r209_initial_that_here_julnji", ["yinya", "julnji", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; julnji tar; yaluy here."),
    row(49, "That mirror is here.", "Yinya kilaja yaluy.", "yinya kilaja yaluy | that mirror here", "r209_initial_that_here_kilaja", ["yinya", "kilaja", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; kilaja mirror; yaluy here.", ["kilaja"]),
    row(50, "That motor car is here.", "Yinya mudaka yaluy.", "yinya mudaka yaluy | that motor.car here", "r209_initial_that_here_mudaka", ["yinya", "mudaka", "yaluy"], "Patz section 3.7 yinya can co-occur with a noun; mudaka motor car; yaluy here.", ["mudaka"]),
]


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)
        loans = json.loads(loans_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("r209_"):
            issues.append(f"{label}: Rule 209 frame must start with r209_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        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 209 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")
            if head in LOAN_HEADS and head not in loans:
                issues.append(f"{label}: loan target {head} missing from loans_used")
            if head not in LOAN_HEADS and head in loans:
                issues.append(f"{label}: non-loan target {head} should not be in loans_used")
        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 artefact-use/source/action 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 209 draft: low-coverage artefact reference lexical expansion after Rule 208",
                "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 entries for baybu, binjin, biyin, dakilji, dingkil-dingkil, jamu, julnji, kilaja, mudaka, and wuba. Selected only bare artefact-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 celestial for too few clean noun targets and death/story/place tails; rejected clothing/adornment because exact deictic surfaces already exist in Batches 229-230; deferred fire because of dense event/procedure traps and synonym pressure; replaced source-backed gilaja with wuba to avoid changing the global g-onset loan lint guard.",
        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 209 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_251.py static guards passed: 50 explicit hand-authored rows, exactly one artefact target noun per row, loan targets recorded, support words recorded, correct five frame bands, no target morphology, and no denied use/source/action English/Kuku fields.",
        artifact_path="batch_scripts/bank_251.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())
