#!/usr/bin/env python3
"""Bank batch-257: Rule 215 second person-quality adjective 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-257"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-257-second-low-frequency-person-quality-adjective-expansion-after-rule214-process.md"

TARGET_HEADS = {
    "bangkarr-wumba": "humble",
    "dukul-dandi": "stubborn",
    "jakay-dandi": "stingy",
    "janbay-janbay": "cheeky",
    "jayarr-jayarr": "pleasant",
    "juburr": "experienced",
    "kulun": "selfish",
    "mara-jalajala": "clumsy",
    "mini-mini": "beautiful",
    "mumbar": "careful",
}
SUPPORT = {"bama", "yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "kari", "bajaku", "jarra", "nyaji-l", "nyajil", "nyajin",
    "nuka", "nukal", "nukan", "dajin", "daji", "daji-l", "mani", "manil", "manin",
    "dunga", "dungay", "dungan", "kada", "kaday", "kadan", "wuna", "wunay", "wunan",
    "bawa", "bawal", "bawan", "waju", "wajul", "wajun", "karrba", "karrbal", "karrban",
    "kuni", "kunil", "kunin", "daya", "dayal", "balka", "balkal", "balkan",
    "yala", "yanyu", "ngayu", "nyulu", "yundu", "yurra", "jana", "ngana",
    "nganya", "yununy", "nyunguny", "workku", "minya", "mayi", "nganka",
    "duray", "jakibiyal", "jaway", "jumbun", "junkali", "barrkawun", "ngulkurrijin",
    "wawu-janka", "walay", "yambal", "minday", "muna", "ngarrku-ngarrku", "malaji",
    "mara-duray", "mara-muna", "jurru-walay", "mala-minya", "mala-kuyu",
}
DENY_ENGLISH = (
    "very", "more", "rather", "not", "no ", "cannot", "can't", "become", "became", "getting",
    "work", "working", "food", "eat", "eating", "give", "giving", "gave", "ask", "asking",
    "talk", "talking", "fight", "fighting", "steal", "stealing", "thief", "hunter", "hunting",
    "tame", "afraid", "brave", "confident", "guilty", "law", "legal", "crocodile", "pig",
    "body", "hand", "neck", "properly", "correctly", "alert", "pleasant to talk", "nice to talk",
)


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 person is humble.", "Bama bangkarr-wumba.", "bama bangkarr-wumba | person humble", "r215_np_adj_bangkarr_wumba", ["bama", "bangkarr-wumba"], "Dictionary bama noun 'people/person'; dictionary bangkarr-wumba adjective 'humble'; Patz section 3.1 adjectives denote properties of nominal referents."),
    row(2, "The person is stubborn.", "Bama dukul-dandi.", "bama dukul-dandi | person stubborn", "r215_np_adj_dukul_dandi", ["bama", "dukul-dandi"], "Dictionary dukul-dandi adjective 'stubborn'; Patz section 3.1 nominal-adjective property support."),
    row(3, "The person is stingy.", "Bama jakay-dandi.", "bama jakay-dandi | person stingy", "r215_np_adj_jakay_dandi", ["bama", "jakay-dandi"], "Dictionary jakay-dandi adjective 'stingy'; neck-compound etymology closed."),
    row(4, "The person is cheeky.", "Bama janbay-janbay.", "bama janbay-janbay | person cheeky", "r215_np_adj_janbay_janbay", ["bama", "janbay-janbay"], "Dictionary janbay-janbay adjective 'cheeky' with usage 'Yurra janbay-janbay'; plural pronoun frame closed."),
    row(5, "The person is pleasant.", "Bama jayarr-jayarr.", "bama jayarr-jayarr | person pleasant", "r215_np_adj_jayarr_jayarr", ["bama", "jayarr-jayarr"], "Dictionary jayarr-jayarr adjective 'pleasant, nice to talk to'; speech/talking complement closed."),
    row(6, "The person is experienced.", "Bama juburr.", "bama juburr | person experienced", "r215_np_adj_juburr", ["bama", "juburr"], "Dictionary juburr adjective 'experienced, expert, clever at something'; activity complement closed."),
    row(7, "The person is selfish.", "Bama kulun.", "bama kulun | person selfish", "r215_np_adj_kulun", ["bama", "kulun"], "Dictionary kulun adjective 'selfish'; food/giving usage closed."),
    row(8, "The person is clumsy.", "Bama mara-jalajala.", "bama mara-jalajala | person clumsy", "r215_np_adj_mara_jalajala", ["bama", "mara-jalajala"], "Dictionary mara-jalajala adjective 'clumsy'; hand-compound etymology closed."),
    row(9, "The person is beautiful.", "Bama mini-mini.", "bama mini-mini | person beautiful", "r215_np_adj_mini_mini", ["bama", "mini-mini"], "Dictionary mini-mini adjective 'beautiful, nice, pretty'; mini/correct derivation closed."),
    row(10, "The person is careful.", "Bama mumbar.", "bama mumbar | person careful", "r215_np_adj_mumbar", ["bama", "mumbar"], "Dictionary mumbar adjective 'proper, correct, careful, alert'; selected careful; crocodile alert example closed."),
    row(11, "The person here is humble.", "Bama bangkarr-wumba yaluy.", "bama bangkarr-wumba yaluy | person humble here", "r215_np_adj_here_bangkarr_wumba", ["bama", "bangkarr-wumba", "yaluy"], "Dictionary bangkarr-wumba adjective 'humble'; Patz section 3.7 yaluy 'here'."),
    row(12, "The person here is stubborn.", "Bama dukul-dandi yaluy.", "bama dukul-dandi yaluy | person stubborn here", "r215_np_adj_here_dukul_dandi", ["bama", "dukul-dandi", "yaluy"], "Dictionary dukul-dandi adjective 'stubborn'; Patz section 3.7 yaluy."),
    row(13, "The person here is stingy.", "Bama jakay-dandi yaluy.", "bama jakay-dandi yaluy | person stingy here", "r215_np_adj_here_jakay_dandi", ["bama", "jakay-dandi", "yaluy"], "Dictionary jakay-dandi adjective 'stingy'; Patz section 3.7 yaluy."),
    row(14, "The person here is cheeky.", "Bama janbay-janbay yaluy.", "bama janbay-janbay yaluy | person cheeky here", "r215_np_adj_here_janbay_janbay", ["bama", "janbay-janbay", "yaluy"], "Dictionary janbay-janbay adjective 'cheeky'; Patz section 3.7 yaluy."),
    row(15, "The person here is pleasant.", "Bama jayarr-jayarr yaluy.", "bama jayarr-jayarr yaluy | person pleasant here", "r215_np_adj_here_jayarr_jayarr", ["bama", "jayarr-jayarr", "yaluy"], "Dictionary jayarr-jayarr adjective 'pleasant'; talk prose closed; Patz section 3.7 yaluy."),
    row(16, "The person here is experienced.", "Bama juburr yaluy.", "bama juburr yaluy | person experienced here", "r215_np_adj_here_juburr", ["bama", "juburr", "yaluy"], "Dictionary juburr adjective 'experienced'; activity complement closed; Patz section 3.7 yaluy."),
    row(17, "The person here is selfish.", "Bama kulun yaluy.", "bama kulun yaluy | person selfish here", "r215_np_adj_here_kulun", ["bama", "kulun", "yaluy"], "Dictionary kulun adjective 'selfish'; food/giving usage closed; Patz section 3.7 yaluy."),
    row(18, "The person here is clumsy.", "Bama mara-jalajala yaluy.", "bama mara-jalajala yaluy | person clumsy here", "r215_np_adj_here_mara_jalajala", ["bama", "mara-jalajala", "yaluy"], "Dictionary mara-jalajala adjective 'clumsy'; Patz section 3.7 yaluy."),
    row(19, "The person here is beautiful.", "Bama mini-mini yaluy.", "bama mini-mini yaluy | person beautiful here", "r215_np_adj_here_mini_mini", ["bama", "mini-mini", "yaluy"], "Dictionary mini-mini adjective 'beautiful'; Patz section 3.7 yaluy."),
    row(20, "The person here is careful.", "Bama mumbar yaluy.", "bama mumbar yaluy | person careful here", "r215_np_adj_here_mumbar", ["bama", "mumbar", "yaluy"], "Dictionary mumbar adjective 'careful'; alert/crocodile example closed; Patz section 3.7 yaluy."),
    row(21, "The person there is humble.", "Bama bangkarr-wumba yinyay.", "bama bangkarr-wumba yinyay | person humble there", "r215_np_adj_there_bangkarr_wumba", ["bama", "bangkarr-wumba", "yinyay"], "Dictionary bangkarr-wumba adjective 'humble'; Patz section 3.7 yinyay 'there'."),
    row(22, "The person there is stubborn.", "Bama dukul-dandi yinyay.", "bama dukul-dandi yinyay | person stubborn there", "r215_np_adj_there_dukul_dandi", ["bama", "dukul-dandi", "yinyay"], "Dictionary dukul-dandi adjective 'stubborn'; Patz section 3.7 yinyay."),
    row(23, "The person there is stingy.", "Bama jakay-dandi yinyay.", "bama jakay-dandi yinyay | person stingy there", "r215_np_adj_there_jakay_dandi", ["bama", "jakay-dandi", "yinyay"], "Dictionary jakay-dandi adjective 'stingy'; Patz section 3.7 yinyay."),
    row(24, "The person there is cheeky.", "Bama janbay-janbay yinyay.", "bama janbay-janbay yinyay | person cheeky there", "r215_np_adj_there_janbay_janbay", ["bama", "janbay-janbay", "yinyay"], "Dictionary janbay-janbay adjective 'cheeky'; Patz section 3.7 yinyay."),
    row(25, "The person there is pleasant.", "Bama jayarr-jayarr yinyay.", "bama jayarr-jayarr yinyay | person pleasant there", "r215_np_adj_there_jayarr_jayarr", ["bama", "jayarr-jayarr", "yinyay"], "Dictionary jayarr-jayarr adjective 'pleasant'; Patz section 3.7 yinyay."),
    row(26, "The person there is experienced.", "Bama juburr yinyay.", "bama juburr yinyay | person experienced there", "r215_np_adj_there_juburr", ["bama", "juburr", "yinyay"], "Dictionary juburr adjective 'experienced'; Patz section 3.7 yinyay."),
    row(27, "The person there is selfish.", "Bama kulun yinyay.", "bama kulun yinyay | person selfish there", "r215_np_adj_there_kulun", ["bama", "kulun", "yinyay"], "Dictionary kulun adjective 'selfish'; Patz section 3.7 yinyay."),
    row(28, "The person there is clumsy.", "Bama mara-jalajala yinyay.", "bama mara-jalajala yinyay | person clumsy there", "r215_np_adj_there_mara_jalajala", ["bama", "mara-jalajala", "yinyay"], "Dictionary mara-jalajala adjective 'clumsy'; Patz section 3.7 yinyay."),
    row(29, "The person there is beautiful.", "Bama mini-mini yinyay.", "bama mini-mini yinyay | person beautiful there", "r215_np_adj_there_mini_mini", ["bama", "mini-mini", "yinyay"], "Dictionary mini-mini adjective 'beautiful'; Patz section 3.7 yinyay."),
    row(30, "The person there is careful.", "Bama mumbar yinyay.", "bama mumbar yinyay | person careful there", "r215_np_adj_there_mumbar", ["bama", "mumbar", "yinyay"], "Dictionary mumbar adjective 'careful'; Patz section 3.7 yinyay."),
    row(31, "That person is humble.", "Yinya bama bangkarr-wumba.", "yinya bama bangkarr-wumba | that person humble", "r215_that_np_adj_bangkarr_wumba", ["yinya", "bama", "bangkarr-wumba"], "Patz section 3.7 yinya can co-occur with a noun; dictionary bangkarr-wumba adjective 'humble'."),
    row(32, "That person is stubborn.", "Yinya bama dukul-dandi.", "yinya bama dukul-dandi | that person stubborn", "r215_that_np_adj_dukul_dandi", ["yinya", "bama", "dukul-dandi"], "Patz section 3.7 yinya can co-occur with a noun; dictionary dukul-dandi adjective 'stubborn'."),
    row(33, "That person is stingy.", "Yinya bama jakay-dandi.", "yinya bama jakay-dandi | that person stingy", "r215_that_np_adj_jakay_dandi", ["yinya", "bama", "jakay-dandi"], "Patz section 3.7 yinya can co-occur with a noun; dictionary jakay-dandi adjective 'stingy'."),
    row(34, "That person is cheeky.", "Yinya bama janbay-janbay.", "yinya bama janbay-janbay | that person cheeky", "r215_that_np_adj_janbay_janbay", ["yinya", "bama", "janbay-janbay"], "Patz section 3.7 yinya can co-occur with a noun; dictionary janbay-janbay adjective 'cheeky'."),
    row(35, "That person is pleasant.", "Yinya bama jayarr-jayarr.", "yinya bama jayarr-jayarr | that person pleasant", "r215_that_np_adj_jayarr_jayarr", ["yinya", "bama", "jayarr-jayarr"], "Patz section 3.7 yinya can co-occur with a noun; dictionary jayarr-jayarr adjective 'pleasant'."),
    row(36, "That person is experienced.", "Yinya bama juburr.", "yinya bama juburr | that person experienced", "r215_that_np_adj_juburr", ["yinya", "bama", "juburr"], "Patz section 3.7 yinya can co-occur with a noun; dictionary juburr adjective 'experienced'."),
    row(37, "That person is selfish.", "Yinya bama kulun.", "yinya bama kulun | that person selfish", "r215_that_np_adj_kulun", ["yinya", "bama", "kulun"], "Patz section 3.7 yinya can co-occur with a noun; dictionary kulun adjective 'selfish'."),
    row(38, "That person is clumsy.", "Yinya bama mara-jalajala.", "yinya bama mara-jalajala | that person clumsy", "r215_that_np_adj_mara_jalajala", ["yinya", "bama", "mara-jalajala"], "Patz section 3.7 yinya can co-occur with a noun; dictionary mara-jalajala adjective 'clumsy'."),
    row(39, "That person is beautiful.", "Yinya bama mini-mini.", "yinya bama mini-mini | that person beautiful", "r215_that_np_adj_mini_mini", ["yinya", "bama", "mini-mini"], "Patz section 3.7 yinya can co-occur with a noun; dictionary mini-mini adjective 'beautiful'."),
    row(40, "That person is careful.", "Yinya bama mumbar.", "yinya bama mumbar | that person careful", "r215_that_np_adj_mumbar", ["yinya", "bama", "mumbar"], "Patz section 3.7 yinya can co-occur with a noun; dictionary mumbar adjective 'careful'."),
    row(41, "That person there is humble.", "Yinya bama bangkarr-wumba yinyay.", "yinya bama bangkarr-wumba yinyay | that person humble there", "r215_that_np_adj_there_bangkarr_wumba", ["yinya", "bama", "bangkarr-wumba", "yinyay"], "Patz section 3.7 yinya with noun; dictionary bangkarr-wumba adjective 'humble'; yinyay 'there'."),
    row(42, "That person there is stubborn.", "Yinya bama dukul-dandi yinyay.", "yinya bama dukul-dandi yinyay | that person stubborn there", "r215_that_np_adj_there_dukul_dandi", ["yinya", "bama", "dukul-dandi", "yinyay"], "Patz section 3.7 yinya with noun; dictionary dukul-dandi adjective 'stubborn'; yinyay 'there'."),
    row(43, "That person there is stingy.", "Yinya bama jakay-dandi yinyay.", "yinya bama jakay-dandi yinyay | that person stingy there", "r215_that_np_adj_there_jakay_dandi", ["yinya", "bama", "jakay-dandi", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jakay-dandi adjective 'stingy'; yinyay 'there'."),
    row(44, "That person there is cheeky.", "Yinya bama janbay-janbay yinyay.", "yinya bama janbay-janbay yinyay | that person cheeky there", "r215_that_np_adj_there_janbay_janbay", ["yinya", "bama", "janbay-janbay", "yinyay"], "Patz section 3.7 yinya with noun; dictionary janbay-janbay adjective 'cheeky'; yinyay 'there'."),
    row(45, "That person there is pleasant.", "Yinya bama jayarr-jayarr yinyay.", "yinya bama jayarr-jayarr yinyay | that person pleasant there", "r215_that_np_adj_there_jayarr_jayarr", ["yinya", "bama", "jayarr-jayarr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jayarr-jayarr adjective 'pleasant'; yinyay 'there'."),
    row(46, "That person there is experienced.", "Yinya bama juburr yinyay.", "yinya bama juburr yinyay | that person experienced there", "r215_that_np_adj_there_juburr", ["yinya", "bama", "juburr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary juburr adjective 'experienced'; yinyay 'there'."),
    row(47, "That person there is selfish.", "Yinya bama kulun yinyay.", "yinya bama kulun yinyay | that person selfish there", "r215_that_np_adj_there_kulun", ["yinya", "bama", "kulun", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kulun adjective 'selfish'; yinyay 'there'."),
    row(48, "That person there is clumsy.", "Yinya bama mara-jalajala yinyay.", "yinya bama mara-jalajala yinyay | that person clumsy there", "r215_that_np_adj_there_mara_jalajala", ["yinya", "bama", "mara-jalajala", "yinyay"], "Patz section 3.7 yinya with noun; dictionary mara-jalajala adjective 'clumsy'; yinyay 'there'."),
    row(49, "That person there is beautiful.", "Yinya bama mini-mini yinyay.", "yinya bama mini-mini yinyay | that person beautiful there", "r215_that_np_adj_there_mini_mini", ["yinya", "bama", "mini-mini", "yinyay"], "Patz section 3.7 yinya with noun; dictionary mini-mini adjective 'beautiful'; yinyay 'there'."),
    row(50, "That person there is careful.", "Yinya bama mumbar yinyay.", "yinya bama mumbar yinyay | that person careful there", "r215_that_np_adj_there_mumbar", ["yinya", "bama", "mumbar", "yinyay"], "Patz section 3.7 yinya with noun; dictionary mumbar adjective 'careful'; yinyay 'there'."),
]


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("r215_"):
            issues.append(f"{label}: Rule 215 frame must start with r215_")
        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 215")
        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 215 target adjective, found {targets}")
        if not has_token(low, "bama"):
            issues.append(f"{label}: every Rule 215 row requires bama support noun")
        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, "yaluy") or has_token(low, "yinyay") or len(low.split()) != 2):
            issues.append(f"{label}: rows 1-10 require Bama TARGET")
        if 11 <= seq <= 20 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 11-20 require Bama TARGET yaluy")
        if 21 <= seq <= 30 and (has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 21-30 require Bama TARGET yinyay")
        if 31 <= seq <= 40 and (not low.startswith("yinya bama ") or has_token(low, "yaluy") or has_token(low, "yinyay") or len(low.split()) != 3):
            issues.append(f"{label}: rows 31-40 require Yinya bama TARGET")
        if 41 <= seq <= 50 and (not low.startswith("yinya bama ") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 4):
            issues.append(f"{label}: rows 41-50 require Yinya bama TARGET yinyay")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied degree/negation/event/social-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 215 draft: second low-frequency person-quality adjective expansion after Rule 214",
                "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 nominal/adjective property basis, Patz section 3.7 yinya/yaluy/yinyay support, "
            "and dictionary entries for bama plus bangkarr-wumba, dukul-dandi, jakay-dandi, janbay-janbay, "
            "jayarr-jayarr, juburr, kulun, mara-jalajala, mini-mini, and mumbar. Admitted only selected person-quality senses."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail=(
            "Selected second person-quality adjective pass because the same sourced bama adjective frames remain safe. "
            "Rejected food-reference for cooking/leaching/loan/medicine/alcohol tails; held minday/muna for animal-tameness pressure, "
            "ngarrku-ngarrku for work/complement pressure, and malaji for legal/social-event pressure."
        ),
        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 215 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="python3 batch_scripts/bank_257.py cross-corpus duplicate scan",
        artifact_path="batch_scripts/bank_257.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail=(
            "bank_257.py static guards passed: 50 explicit hand-authored rows, exactly one Rule 215 person-quality target adjective per row, "
            "bama support noun in every row, no loans, no target morphology, no degree/negation/social-action/work-food-hunting/motion-event English, "
            "and only the five sourced frame bands."
        ),
        artifact_path="batch_scripts/bank_257.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())
