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

TARGET_HEADS = {
    "duray": "tricky",
    "jakibiyal": "tough",
    "jaway": "generous",
    "jumbun": "greedy",
    "junkali": "truthful",
    "barrkawun": "unskilled",
    "ngulkurrijin": "beautiful",
    "wawu-janka": "quiet",
    "walay": "skilled",
    "yambal": "slow",
}
SUPPORT = {"bama", "yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "kari", "bajaku", "jarra", "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",
    "yala", "yanyu", "ngayu", "nyulu", "yundu", "jana", "ngana", "nganya", "yununy", "nyunguny",
    "balbi", "minya", "mayi", "workku", "mara", "mara-duray", "waral-dandi", "jurru-walay",
    "kiray", "manun-manun", "barrangkul", "jalngka", "kurru-kurru", "darra", "yalmbar",
    "murru", "murru-murru", "muru-muru", "mulun", "dangal", "dulngki", "dungkul",
    "dunju-dunju", "jala-jala", "jalkar-jalkar", "yuku", "muja-muja", "nguyal",
}
DENY_ENGLISH = (
    "very", "more", "rather", "not", "no ", "cannot", "can't", "become", "became", "getting", "working",
    "work", "food", "eat", "eating", "hunter", "hunting", "shooter", "shooting", "fight", "fighting",
    "steal", "stealing", "thief", "complain", "complaining", "argue", "arguing", "ask", "asking",
    "mercy", "merciful", "kind", "quietly", "secretly", "motion", "walking", "running", "slowly",
    "flower", "old man", "real aboriginal", "relationship", "forbidden", "prohibited",
)


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 tricky.", "Bama duray.", "bama duray | person tricky", "r214_np_adj_duray", ["bama", "duray"], "Dictionary bama noun 'people, mankind'; dictionary duray adjective 'tricky, clever'; Patz section 3.1 adjectives denote properties of nominal referents."),
    row(2, "The person is tough.", "Bama jakibiyal.", "bama jakibiyal | person tough", "r214_np_adj_jakibiyal", ["bama", "jakibiyal"], "Dictionary bama noun 'people'; dictionary jakibiyal adjective 'tough, strong'; Patz section 3.1 nominal-adjective predicate support."),
    row(3, "The person is generous.", "Bama jaway.", "bama jaway | person generous", "r214_np_adj_jaway", ["bama", "jaway"], "Dictionary bama noun 'people'; dictionary jaway adjective 'generous, liberal'; Patz section 3.1 adjective property support."),
    row(4, "The person is greedy.", "Bama jumbun.", "bama jumbun | person greedy", "r214_np_adj_jumbun", ["bama", "jumbun"], "Dictionary bama noun 'people'; dictionary jumbun adjective 'greedy'; food/eating prose closed; Patz section 3.1."),
    row(5, "The person is truthful.", "Bama junkali.", "bama junkali | person truthful", "r214_np_adj_junkali", ["bama", "junkali"], "Dictionary bama noun 'people'; dictionary junkali adjective 'truthful, straight' with usage 'Nyulu junkali'; Patz section 3.1."),
    row(6, "The person is unskilled.", "Bama barrkawun.", "bama barrkawun | person unskilled", "r214_np_adj_barrkawun", ["bama", "barrkawun"], "Dictionary bama noun 'people'; dictionary barrkawun adjective translation 'unskilled', definition 'not good at something'; no negation particle opened."),
    row(7, "The person is beautiful.", "Bama ngulkurrijin.", "bama ngulkurrijin | person beautiful", "r214_np_adj_ngulkurrijin", ["bama", "ngulkurrijin"], "Dictionary bama noun 'people'; dictionary ngulkurrijin adjective 'pretty, beautiful'; flower usage closed; Patz section 3.1."),
    row(8, "The person is quiet.", "Bama wawu-janka.", "bama wawu-janka | person quiet", "r214_np_adj_wawu_janka", ["bama", "wawu-janka"], "Dictionary bama noun 'people'; dictionary wawu-janka adjective 'quiet', definition 'a quiet person'; Patz section 3.1."),
    row(9, "The person is skilled.", "Bama walay.", "bama walay | person skilled", "r214_np_adj_walay", ["bama", "walay"], "Dictionary bama noun 'people'; dictionary walay adjective 'proficient, skilled'; work/food/hunting prose closed."),
    row(10, "The person is slow.", "Bama yambal.", "bama yambal | person slow", "r214_np_adj_yambal", ["bama", "yambal"], "Dictionary bama noun 'people'; dictionary yambal adjective 'slow'; motion-event prose closed; Patz section 3.1."),
    row(11, "The person here is tricky.", "Bama duray yaluy.", "bama duray yaluy | person tricky here", "r214_np_adj_here_duray", ["bama", "duray", "yaluy"], "Dictionary duray adjective 'tricky'; Patz section 3.7 yaluy 'here'."),
    row(12, "The person here is tough.", "Bama jakibiyal yaluy.", "bama jakibiyal yaluy | person tough here", "r214_np_adj_here_jakibiyal", ["bama", "jakibiyal", "yaluy"], "Dictionary jakibiyal adjective 'tough, strong'; Patz section 3.7 yaluy 'here'."),
    row(13, "The person here is generous.", "Bama jaway yaluy.", "bama jaway yaluy | person generous here", "r214_np_adj_here_jaway", ["bama", "jaway", "yaluy"], "Dictionary jaway adjective 'generous, liberal'; Patz section 3.7 yaluy 'here'."),
    row(14, "The person here is greedy.", "Bama jumbun yaluy.", "bama jumbun yaluy | person greedy here", "r214_np_adj_here_jumbun", ["bama", "jumbun", "yaluy"], "Dictionary jumbun adjective 'greedy'; food/eating prose closed; Patz section 3.7 yaluy."),
    row(15, "The person here is truthful.", "Bama junkali yaluy.", "bama junkali yaluy | person truthful here", "r214_np_adj_here_junkali", ["bama", "junkali", "yaluy"], "Dictionary junkali adjective 'truthful, straight'; Patz section 3.7 yaluy 'here'."),
    row(16, "The person here is unskilled.", "Bama barrkawun yaluy.", "bama barrkawun yaluy | person unskilled here", "r214_np_adj_here_barrkawun", ["bama", "barrkawun", "yaluy"], "Dictionary barrkawun adjective 'unskilled'; no independent kari; Patz section 3.7 yaluy."),
    row(17, "The person here is beautiful.", "Bama ngulkurrijin yaluy.", "bama ngulkurrijin yaluy | person beautiful here", "r214_np_adj_here_ngulkurrijin", ["bama", "ngulkurrijin", "yaluy"], "Dictionary ngulkurrijin adjective 'pretty, beautiful'; Patz section 3.7 yaluy."),
    row(18, "The person here is quiet.", "Bama wawu-janka yaluy.", "bama wawu-janka yaluy | person quiet here", "r214_np_adj_here_wawu_janka", ["bama", "wawu-janka", "yaluy"], "Dictionary wawu-janka adjective 'quiet'; Patz section 3.7 yaluy 'here'."),
    row(19, "The person here is skilled.", "Bama walay yaluy.", "bama walay yaluy | person skilled here", "r214_np_adj_here_walay", ["bama", "walay", "yaluy"], "Dictionary walay adjective 'proficient, skilled'; work/getting-food prose closed; Patz section 3.7 yaluy."),
    row(20, "The person here is slow.", "Bama yambal yaluy.", "bama yambal yaluy | person slow here", "r214_np_adj_here_yambal", ["bama", "yambal", "yaluy"], "Dictionary yambal adjective 'slow'; motion-event prose closed; Patz section 3.7 yaluy."),
    row(21, "The person there is tricky.", "Bama duray yinyay.", "bama duray yinyay | person tricky there", "r214_np_adj_there_duray", ["bama", "duray", "yinyay"], "Dictionary duray adjective 'tricky'; Patz section 3.7 yinyay 'there'."),
    row(22, "The person there is tough.", "Bama jakibiyal yinyay.", "bama jakibiyal yinyay | person tough there", "r214_np_adj_there_jakibiyal", ["bama", "jakibiyal", "yinyay"], "Dictionary jakibiyal adjective 'tough, strong'; Patz section 3.7 yinyay."),
    row(23, "The person there is generous.", "Bama jaway yinyay.", "bama jaway yinyay | person generous there", "r214_np_adj_there_jaway", ["bama", "jaway", "yinyay"], "Dictionary jaway adjective 'generous, liberal'; Patz section 3.7 yinyay."),
    row(24, "The person there is greedy.", "Bama jumbun yinyay.", "bama jumbun yinyay | person greedy there", "r214_np_adj_there_jumbun", ["bama", "jumbun", "yinyay"], "Dictionary jumbun adjective 'greedy'; no eating/food event; Patz section 3.7 yinyay."),
    row(25, "The person there is truthful.", "Bama junkali yinyay.", "bama junkali yinyay | person truthful there", "r214_np_adj_there_junkali", ["bama", "junkali", "yinyay"], "Dictionary junkali adjective 'truthful, straight'; Patz section 3.7 yinyay."),
    row(26, "The person there is unskilled.", "Bama barrkawun yinyay.", "bama barrkawun yinyay | person unskilled there", "r214_np_adj_there_barrkawun", ["bama", "barrkawun", "yinyay"], "Dictionary barrkawun adjective 'unskilled'; no negation morphology; Patz section 3.7 yinyay."),
    row(27, "The person there is beautiful.", "Bama ngulkurrijin yinyay.", "bama ngulkurrijin yinyay | person beautiful there", "r214_np_adj_there_ngulkurrijin", ["bama", "ngulkurrijin", "yinyay"], "Dictionary ngulkurrijin adjective 'beautiful'; Patz section 3.7 yinyay."),
    row(28, "The person there is quiet.", "Bama wawu-janka yinyay.", "bama wawu-janka yinyay | person quiet there", "r214_np_adj_there_wawu_janka", ["bama", "wawu-janka", "yinyay"], "Dictionary wawu-janka adjective 'quiet'; Patz section 3.7 yinyay."),
    row(29, "The person there is skilled.", "Bama walay yinyay.", "bama walay yinyay | person skilled there", "r214_np_adj_there_walay", ["bama", "walay", "yinyay"], "Dictionary walay adjective 'skilled'; work/food/hunting prose closed; Patz section 3.7 yinyay."),
    row(30, "The person there is slow.", "Bama yambal yinyay.", "bama yambal yinyay | person slow there", "r214_np_adj_there_yambal", ["bama", "yambal", "yinyay"], "Dictionary yambal adjective 'slow'; motion-event prose closed; Patz section 3.7 yinyay."),
    row(31, "That person is tricky.", "Yinya bama duray.", "yinya bama duray | that person tricky", "r214_that_np_adj_duray", ["yinya", "bama", "duray"], "Patz section 3.7 yinya can co-occur with a noun; dictionary duray adjective 'tricky'."),
    row(32, "That person is tough.", "Yinya bama jakibiyal.", "yinya bama jakibiyal | that person tough", "r214_that_np_adj_jakibiyal", ["yinya", "bama", "jakibiyal"], "Patz section 3.7 yinya can co-occur with a noun; dictionary jakibiyal adjective 'tough'."),
    row(33, "That person is generous.", "Yinya bama jaway.", "yinya bama jaway | that person generous", "r214_that_np_adj_jaway", ["yinya", "bama", "jaway"], "Patz section 3.7 yinya can co-occur with a noun; dictionary jaway adjective 'generous'."),
    row(34, "That person is greedy.", "Yinya bama jumbun.", "yinya bama jumbun | that person greedy", "r214_that_np_adj_jumbun", ["yinya", "bama", "jumbun"], "Patz section 3.7 yinya can co-occur with a noun; dictionary jumbun adjective 'greedy'."),
    row(35, "That person is truthful.", "Yinya bama junkali.", "yinya bama junkali | that person truthful", "r214_that_np_adj_junkali", ["yinya", "bama", "junkali"], "Patz section 3.7 yinya can co-occur with a noun; dictionary junkali adjective 'truthful'."),
    row(36, "That person is unskilled.", "Yinya bama barrkawun.", "yinya bama barrkawun | that person unskilled", "r214_that_np_adj_barrkawun", ["yinya", "bama", "barrkawun"], "Patz section 3.7 yinya can co-occur with a noun; dictionary barrkawun adjective 'unskilled'."),
    row(37, "That person is beautiful.", "Yinya bama ngulkurrijin.", "yinya bama ngulkurrijin | that person beautiful", "r214_that_np_adj_ngulkurrijin", ["yinya", "bama", "ngulkurrijin"], "Patz section 3.7 yinya can co-occur with a noun; dictionary ngulkurrijin adjective 'beautiful'."),
    row(38, "That person is quiet.", "Yinya bama wawu-janka.", "yinya bama wawu-janka | that person quiet", "r214_that_np_adj_wawu_janka", ["yinya", "bama", "wawu-janka"], "Patz section 3.7 yinya can co-occur with a noun; dictionary wawu-janka adjective 'quiet'."),
    row(39, "That person is skilled.", "Yinya bama walay.", "yinya bama walay | that person skilled", "r214_that_np_adj_walay", ["yinya", "bama", "walay"], "Patz section 3.7 yinya can co-occur with a noun; dictionary walay adjective 'skilled'."),
    row(40, "That person is slow.", "Yinya bama yambal.", "yinya bama yambal | that person slow", "r214_that_np_adj_yambal", ["yinya", "bama", "yambal"], "Patz section 3.7 yinya can co-occur with a noun; dictionary yambal adjective 'slow'."),
    row(41, "That person there is tricky.", "Yinya bama duray yinyay.", "yinya bama duray yinyay | that person tricky there", "r214_that_np_adj_there_duray", ["yinya", "bama", "duray", "yinyay"], "Patz section 3.7 yinya with noun; dictionary duray adjective 'tricky'; yinyay 'there'."),
    row(42, "That person there is tough.", "Yinya bama jakibiyal yinyay.", "yinya bama jakibiyal yinyay | that person tough there", "r214_that_np_adj_there_jakibiyal", ["yinya", "bama", "jakibiyal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jakibiyal adjective 'tough'; yinyay 'there'."),
    row(43, "That person there is generous.", "Yinya bama jaway yinyay.", "yinya bama jaway yinyay | that person generous there", "r214_that_np_adj_there_jaway", ["yinya", "bama", "jaway", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jaway adjective 'generous'; yinyay 'there'."),
    row(44, "That person there is greedy.", "Yinya bama jumbun yinyay.", "yinya bama jumbun yinyay | that person greedy there", "r214_that_np_adj_there_jumbun", ["yinya", "bama", "jumbun", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jumbun adjective 'greedy'; yinyay 'there'."),
    row(45, "That person there is truthful.", "Yinya bama junkali yinyay.", "yinya bama junkali yinyay | that person truthful there", "r214_that_np_adj_there_junkali", ["yinya", "bama", "junkali", "yinyay"], "Patz section 3.7 yinya with noun; dictionary junkali adjective 'truthful'; yinyay 'there'."),
    row(46, "That person there is unskilled.", "Yinya bama barrkawun yinyay.", "yinya bama barrkawun yinyay | that person unskilled there", "r214_that_np_adj_there_barrkawun", ["yinya", "bama", "barrkawun", "yinyay"], "Patz section 3.7 yinya with noun; dictionary barrkawun adjective 'unskilled'; yinyay 'there'."),
    row(47, "That person there is beautiful.", "Yinya bama ngulkurrijin yinyay.", "yinya bama ngulkurrijin yinyay | that person beautiful there", "r214_that_np_adj_there_ngulkurrijin", ["yinya", "bama", "ngulkurrijin", "yinyay"], "Patz section 3.7 yinya with noun; dictionary ngulkurrijin adjective 'beautiful'; yinyay 'there'."),
    row(48, "That person there is quiet.", "Yinya bama wawu-janka yinyay.", "yinya bama wawu-janka yinyay | that person quiet there", "r214_that_np_adj_there_wawu_janka", ["yinya", "bama", "wawu-janka", "yinyay"], "Patz section 3.7 yinya with noun; dictionary wawu-janka adjective 'quiet'; yinyay 'there'."),
    row(49, "That person there is skilled.", "Yinya bama walay yinyay.", "yinya bama walay yinyay | that person skilled there", "r214_that_np_adj_there_walay", ["yinya", "bama", "walay", "yinyay"], "Patz section 3.7 yinya with noun; dictionary walay adjective 'skilled'; yinyay 'there'."),
    row(50, "That person there is slow.", "Yinya bama yambal yinyay.", "yinya bama yambal yinyay | that person slow there", "r214_that_np_adj_there_yambal", ["yinya", "bama", "yambal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary yambal adjective 'slow'; 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("r214_"):
            issues.append(f"{label}: Rule 214 frame must start with r214_")
        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 214")
        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 214 target adjective, found {targets}")
        if not has_token(low, "bama"):
            issues.append(f"{label}: every Rule 214 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 214 draft: low-frequency person-quality adjective expansion after Rule 213",
                "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.1 nominal/adjective property basis, Patz section 3.7 yinya/yaluy/yinyay support, dictionary bama, and low-frequency person-quality adjective entries for duray, jakibiyal, jaway, jumbun, junkali, barrkawun, ngulkurrijin, wawu-janka, walay, and yambal.",
        command="rg readback over dictionary.yaml plus grammar.md Patz sections 3.1 and 3.7 checks",
        output_excerpt="bama people; duray tricky/clever; jakibiyal tough/strong; jaway generous/liberal; jumbun greedy; junkali truthful/straight; barrkawun unskilled; ngulkurrijin pretty/beautiful; wawu-janka quiet person; walay proficient/skilled; yambal slow.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail="Selected person-quality adjectives because they fit the sourced NP ADJ frames. Rejected shelter/dwelling for too few clean heads; rejected celestial for too few noun heads after excluding compounds/story/place tails; rejected sky-weather because it was already covered and event-heavy; rejected texture-only because too few unused clean adjectives remained. Closed degree, negation, privative, social-action, work, food, hunting, motion, and event prose.",
        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 214 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="sqlite3 duplicate-preflight over planned Bama ADJ 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_256.py static guards passed: 50 explicit hand-authored rows, exactly one person-quality target adjective per row, bama support in every row, support words recorded, correct five frame bands, no target morphology, no loans, and no denied degree/negation/event/social-action English/Kuku fields.",
        artifact_path="batch_scripts/bank_256.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())
