#!/usr/bin/env python3
"""Bank batch-228: Rule 186 landform reference construction consolidation after Rule 185."""

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-228"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-228-landform-reference-construction-consolidation-after-rule185-process.md"

TARGET_HEADS = {
    "binda-dijarr": "stony crossing",
    "duli": "burnt patch of grass",
    "jamar": "newly cleared scrub",
    "kabay": "small ant bed",
    "karrangkal": "reef",
    "kuri": "small patch of scrub",
    "ngamar": "cliff",
    "nganyay": "desert",
    "ngidin": "boundary",
    "warrmba": "exposed place",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "damu", "naka", "kurrkal", "ngunnga", "nurru", "nyamun", "walba-murru", "yikin",
    "ngunnga-bungal", "warrmba-bungal", "bubu", "baral", "bana", "baya", "kubu",
    "biyin", "gilaja", "binjin", "julnji", "nyumbirr", "wawu-juljal",
}
DENY_ENGLISH = (
    "place-name", "river", "water", "road", "path", "track", "trail", "travel", "walk", "walking", "route",
    "shortcut", "slope", "person facing", "ants", "insect", "corroboree", "ancestral", "home out west",
    "special dance", "rubbish", "debris", "beach", "leaf", "mould", "growing", "bank or river", "fire",
    "burns", "burning", "clear", "clears", "clearing", "land-use", "coral", "sea", "ocean", "collect",
    "collecting", "habitat", "climb", "climbs", "climbing", "fall", "falls", "falling", "danger", "heat",
    "scarcity", "ownership", "dispute", "legal", "border-crossing", "find", "finds", "found", "peep",
    "peeps", "peeping", "causative", "dialect", "loan", "use", "uses", "used", "using", "material",
    "source", "possess", "possession", "plural", "many", "productive reduplication", "reduplicate", "event",
)


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, 4, js(words), js([]), evidence, "0.84")


ROWS = [
    row(1, "The stony crossing is there.", "Binda-dijarr yinyay.", "binda-dijarr yinyay | stony.crossing there", "r186_deictic_binda_dijarr_there", ["binda-dijarr", "yinyay"], "Rule 186 retains binda-dijarr as stony crossing and rotates to yinyay deictic support."),
    row(2, "The burnt patch of grass is there.", "Duli yinyay.", "duli yinyay | burnt.patch.of.grass there", "r186_deictic_duli_there", ["duli", "yinyay"], "Rule 186 retains duli as burnt patch of grass; no fire/burning event row."),
    row(3, "The newly cleared scrub is there.", "Jamar yinyay.", "jamar yinyay | newly.cleared.scrub there", "r186_deictic_jamar_there", ["jamar", "yinyay"], "Rule 186 retains jamar as newly cleared scrub; no clearing action row."),
    row(4, "The small ant bed is there.", "Kabay yinyay.", "kabay yinyay | small.ant.bed there", "r186_deictic_kabay_there", ["kabay", "yinyay"], "Rule 186 retains kabay as small ant bed; no ant/insect behavior row."),
    row(5, "The reef is there.", "Karrangkal yinyay.", "karrangkal yinyay | reef there", "r186_deictic_karrangkal_there", ["karrangkal", "yinyay"], "Rule 186 retains karrangkal as reef; coral/sea/water claims closed."),
    row(6, "The small patch of scrub is there.", "Kuri yinyay.", "kuri yinyay | small.patch.of.scrub there", "r186_deictic_kuri_there", ["kuri", "yinyay"], "Rule 186 retains kuri as small patch of scrub; plant-use/ecology closed."),
    row(7, "The cliff is there.", "Ngamar yinyay.", "ngamar yinyay | cliff there", "r186_deictic_ngamar_there", ["ngamar", "yinyay"], "Rule 186 retains ngamar as cliff; no climbing/danger row."),
    row(8, "The desert is there.", "Nganyay yinyay.", "nganyay yinyay | desert there", "r186_deictic_nganyay_there", ["nganyay", "yinyay"], "Rule 186 retains nganyay as desert; no heat/travel/scarcity row."),
    row(9, "The boundary is there.", "Ngidin yinyay.", "ngidin yinyay | boundary there", "r186_deictic_ngidin_there", ["ngidin", "yinyay"], "Rule 186 retains ngidin as boundary; no ownership/dispute row."),
    row(10, "The exposed place is there.", "Warrmba yinyay.", "warrmba yinyay | exposed.place there", "r186_deictic_warrmba_there", ["warrmba", "yinyay"], "Rule 186 retains warrmba as exposed place; no causative/find/peep row."),
    row(11, "I see the stony crossing here.", "Ngayu binda-dijarr yaluy nyajil.", "ngayu binda-dijarr yaluy nyaji-l | I stony.crossing here see-NONPAST", "r186_present_i_binda_dijarr_here", ["ngayu", "binda-dijarr", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; target landform bare."),
    row(12, "I see the burnt patch of grass here.", "Ngayu duli yaluy nyajil.", "ngayu duli yaluy nyaji-l | I burnt.patch.of.grass here see-NONPAST", "r186_present_i_duli_here", ["ngayu", "duli", "yaluy", "nyaji-l"], "First-person present perception; no fire/burning event row."),
    row(13, "I see the newly cleared scrub here.", "Ngayu jamar yaluy nyajil.", "ngayu jamar yaluy nyaji-l | I newly.cleared.scrub here see-NONPAST", "r186_present_i_jamar_here", ["ngayu", "jamar", "yaluy", "nyaji-l"], "First-person present perception; no clearing action row."),
    row(14, "I see the small ant bed here.", "Ngayu kabay yaluy nyajil.", "ngayu kabay yaluy nyaji-l | I small.ant.bed here see-NONPAST", "r186_present_i_kabay_here", ["ngayu", "kabay", "yaluy", "nyaji-l"], "First-person present perception; no ant/insect behavior row."),
    row(15, "I see the reef here.", "Ngayu karrangkal yaluy nyajil.", "ngayu karrangkal yaluy nyaji-l | I reef here see-NONPAST", "r186_present_i_karrangkal_here", ["ngayu", "karrangkal", "yaluy", "nyaji-l"], "First-person present perception; reef only."),
    row(16, "I see the small patch of scrub here.", "Ngayu kuri yaluy nyajil.", "ngayu kuri yaluy nyaji-l | I small.patch.of.scrub here see-NONPAST", "r186_present_i_kuri_here", ["ngayu", "kuri", "yaluy", "nyaji-l"], "First-person present perception; plant-use/ecology closed."),
    row(17, "I see the cliff here.", "Ngayu ngamar yaluy nyajil.", "ngayu ngamar yaluy nyaji-l | I cliff here see-NONPAST", "r186_present_i_ngamar_here", ["ngayu", "ngamar", "yaluy", "nyaji-l"], "First-person present perception; no climbing/danger row."),
    row(18, "I see the desert here.", "Ngayu nganyay yaluy nyajil.", "ngayu nganyay yaluy nyaji-l | I desert here see-NONPAST", "r186_present_i_nganyay_here", ["ngayu", "nganyay", "yaluy", "nyaji-l"], "First-person present perception; desert only."),
    row(19, "I see the boundary here.", "Ngayu ngidin yaluy nyajil.", "ngayu ngidin yaluy nyaji-l | I boundary here see-NONPAST", "r186_present_i_ngidin_here", ["ngayu", "ngidin", "yaluy", "nyaji-l"], "First-person present perception; no ownership/dispute row."),
    row(20, "I see the exposed place here.", "Ngayu warrmba yaluy nyajil.", "ngayu warrmba yaluy nyaji-l | I exposed.place here see-NONPAST", "r186_present_i_warrmba_here", ["ngayu", "warrmba", "yaluy", "nyaji-l"], "First-person present perception; no warrmba-bungal verb row."),
    row(21, "You see the stony crossing here.", "Yundu binda-dijarr yaluy nyajil.", "yundu binda-dijarr yaluy nyaji-l | you stony.crossing here see-NONPAST", "r186_present_you_binda_dijarr_here", ["yundu", "binda-dijarr", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(22, "You see the burnt patch of grass here.", "Yundu duli yaluy nyajil.", "yundu duli yaluy nyaji-l | you burnt.patch.of.grass here see-NONPAST", "r186_present_you_duli_here", ["yundu", "duli", "yaluy", "nyaji-l"], "Second-person present perception; no fire/burning event row."),
    row(23, "You see the newly cleared scrub here.", "Yundu jamar yaluy nyajil.", "yundu jamar yaluy nyaji-l | you newly.cleared.scrub here see-NONPAST", "r186_present_you_jamar_here", ["yundu", "jamar", "yaluy", "nyaji-l"], "Second-person present perception; no clearing action row."),
    row(24, "You see the small ant bed here.", "Yundu kabay yaluy nyajil.", "yundu kabay yaluy nyaji-l | you small.ant.bed here see-NONPAST", "r186_present_you_kabay_here", ["yundu", "kabay", "yaluy", "nyaji-l"], "Second-person present perception; no ant/insect behavior row."),
    row(25, "You see the reef here.", "Yundu karrangkal yaluy nyajil.", "yundu karrangkal yaluy nyaji-l | you reef here see-NONPAST", "r186_present_you_karrangkal_here", ["yundu", "karrangkal", "yaluy", "nyaji-l"], "Second-person present perception; reef only."),
    row(26, "You see the small patch of scrub here.", "Yundu kuri yaluy nyajil.", "yundu kuri yaluy nyaji-l | you small.patch.of.scrub here see-NONPAST", "r186_present_you_kuri_here", ["yundu", "kuri", "yaluy", "nyaji-l"], "Second-person present perception; plant-use/ecology closed."),
    row(27, "You see the cliff here.", "Yundu ngamar yaluy nyajil.", "yundu ngamar yaluy nyaji-l | you cliff here see-NONPAST", "r186_present_you_ngamar_here", ["yundu", "ngamar", "yaluy", "nyaji-l"], "Second-person present perception; no climbing/danger row."),
    row(28, "You see the desert here.", "Yundu nganyay yaluy nyajil.", "yundu nganyay yaluy nyaji-l | you desert here see-NONPAST", "r186_present_you_nganyay_here", ["yundu", "nganyay", "yaluy", "nyaji-l"], "Second-person present perception; desert only."),
    row(29, "You see the boundary here.", "Yundu ngidin yaluy nyajil.", "yundu ngidin yaluy nyaji-l | you boundary here see-NONPAST", "r186_present_you_ngidin_here", ["yundu", "ngidin", "yaluy", "nyaji-l"], "Second-person present perception; no dispute/legal row."),
    row(30, "You see the exposed place here.", "Yundu warrmba yaluy nyajil.", "yundu warrmba yaluy nyaji-l | you exposed.place here see-NONPAST", "r186_present_you_warrmba_here", ["yundu", "warrmba", "yaluy", "nyaji-l"], "Second-person present perception; no causative/find/peep row."),
    row(31, "They saw the stony crossing here.", "Jana binda-dijarr yaluy nyajin.", "jana binda-dijarr yaluy nyaji-ny | they stony.crossing here see-PAST", "r186_past_they_binda_dijarr_here", ["jana", "binda-dijarr", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(32, "They saw the burnt patch of grass here.", "Jana duli yaluy nyajin.", "jana duli yaluy nyaji-ny | they burnt.patch.of.grass here see-PAST", "r186_past_they_duli_here", ["jana", "duli", "yaluy", "nyaji-l"], "Third-person plural past perception; no fire/burning event row."),
    row(33, "They saw the newly cleared scrub here.", "Jana jamar yaluy nyajin.", "jana jamar yaluy nyaji-ny | they newly.cleared.scrub here see-PAST", "r186_past_they_jamar_here", ["jana", "jamar", "yaluy", "nyaji-l"], "Third-person plural past perception; no clearing action row."),
    row(34, "They saw the small ant bed here.", "Jana kabay yaluy nyajin.", "jana kabay yaluy nyaji-ny | they small.ant.bed here see-PAST", "r186_past_they_kabay_here", ["jana", "kabay", "yaluy", "nyaji-l"], "Third-person plural past perception; no ant/insect behavior row."),
    row(35, "They saw the reef here.", "Jana karrangkal yaluy nyajin.", "jana karrangkal yaluy nyaji-ny | they reef here see-PAST", "r186_past_they_karrangkal_here", ["jana", "karrangkal", "yaluy", "nyaji-l"], "Third-person plural past perception; reef only."),
    row(36, "They saw the small patch of scrub here.", "Jana kuri yaluy nyajin.", "jana kuri yaluy nyaji-ny | they small.patch.of.scrub here see-PAST", "r186_past_they_kuri_here", ["jana", "kuri", "yaluy", "nyaji-l"], "Third-person plural past perception; plant-use/ecology closed."),
    row(37, "They saw the cliff here.", "Jana ngamar yaluy nyajin.", "jana ngamar yaluy nyaji-ny | they cliff here see-PAST", "r186_past_they_ngamar_here", ["jana", "ngamar", "yaluy", "nyaji-l"], "Third-person plural past perception; no climbing/danger row."),
    row(38, "They saw the desert here.", "Jana nganyay yaluy nyajin.", "jana nganyay yaluy nyaji-ny | they desert here see-PAST", "r186_past_they_nganyay_here", ["jana", "nganyay", "yaluy", "nyaji-l"], "Third-person plural past perception; desert only."),
    row(39, "They saw the boundary here.", "Jana ngidin yaluy nyajin.", "jana ngidin yaluy nyaji-ny | they boundary here see-PAST", "r186_past_they_ngidin_here", ["jana", "ngidin", "yaluy", "nyaji-l"], "Third-person plural past perception; no dispute/legal row."),
    row(40, "They saw the exposed place here.", "Jana warrmba yaluy nyajin.", "jana warrmba yaluy nyaji-ny | they exposed.place here see-PAST", "r186_past_they_warrmba_here", ["jana", "warrmba", "yaluy", "nyaji-l"], "Third-person plural past perception; no causative/find/peep row."),
    row(41, "We see the stony crossing there.", "Ngana binda-dijarr yinyay nyajil.", "ngana binda-dijarr yinyay nyaji-l | we stony.crossing there see-NONPAST", "r186_present_we_binda_dijarr_there", ["ngana", "binda-dijarr", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(42, "We see the burnt patch of grass there.", "Ngana duli yinyay nyajil.", "ngana duli yinyay nyaji-l | we burnt.patch.of.grass there see-NONPAST", "r186_present_we_duli_there", ["ngana", "duli", "yinyay", "nyaji-l"], "Inclusive present perception; no fire/burning event row."),
    row(43, "We see the newly cleared scrub there.", "Ngana jamar yinyay nyajil.", "ngana jamar yinyay nyaji-l | we newly.cleared.scrub there see-NONPAST", "r186_present_we_jamar_there", ["ngana", "jamar", "yinyay", "nyaji-l"], "Inclusive present perception; no clearing action row."),
    row(44, "We see the small ant bed there.", "Ngana kabay yinyay nyajil.", "ngana kabay yinyay nyaji-l | we small.ant.bed there see-NONPAST", "r186_present_we_kabay_there", ["ngana", "kabay", "yinyay", "nyaji-l"], "Inclusive present perception; no ant/insect behavior row."),
    row(45, "We see the reef there.", "Ngana karrangkal yinyay nyajil.", "ngana karrangkal yinyay nyaji-l | we reef there see-NONPAST", "r186_present_we_karrangkal_there", ["ngana", "karrangkal", "yinyay", "nyaji-l"], "Inclusive present perception; reef only."),
    row(46, "We see the small patch of scrub there.", "Ngana kuri yinyay nyajil.", "ngana kuri yinyay nyaji-l | we small.patch.of.scrub there see-NONPAST", "r186_present_we_kuri_there", ["ngana", "kuri", "yinyay", "nyaji-l"], "Inclusive present perception; plant-use/ecology closed."),
    row(47, "We see the cliff there.", "Ngana ngamar yinyay nyajil.", "ngana ngamar yinyay nyaji-l | we cliff there see-NONPAST", "r186_present_we_ngamar_there", ["ngana", "ngamar", "yinyay", "nyaji-l"], "Inclusive present perception; no climbing/danger row."),
    row(48, "We see the desert there.", "Ngana nganyay yinyay nyajil.", "ngana nganyay yinyay nyaji-l | we desert there see-NONPAST", "r186_present_we_nganyay_there", ["ngana", "nganyay", "yinyay", "nyaji-l"], "Inclusive present perception; desert only."),
    row(49, "We see the boundary there.", "Ngana ngidin yinyay nyajil.", "ngana ngidin yinyay nyaji-l | we boundary there see-NONPAST", "r186_present_we_ngidin_there", ["ngana", "ngidin", "yinyay", "nyaji-l"], "Inclusive present perception; no dispute/legal row."),
    row(50, "We see the exposed place there.", "Ngana warrmba yinyay nyajil.", "ngana warrmba yinyay nyaji-l | we exposed.place there see-NONPAST", "r186_present_we_warrmba_there", ["ngana", "warrmba", "yinyay", "nyaji-l"], "Inclusive present perception; no causative/find/peep row."),
]


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


def first_word(low: str) -> str:
    return low.split()[0].strip(".,!?;:\"")


def has_target_case(low: str, head: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?: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)\b", low) is not None


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


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"{LABEL}: expected 50 rows, found {len(ROWS)}")
    seen_ku: set[str] = set()
    for expected, row_data in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row_data
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        if seq != expected:
            issues.append(f"{label}: sequence mismatch; expected {expected}")
        if not english[:1].isupper() or english[-1:] not in ".!?":
            issues.append(f"{label}: English punctuation/capitalization failure")
        if " | " not in analysis:
            issues.append(f"{label}: analysis missing gloss separator")
        if not frame.startswith("r186_"):
            issues.append(f"{label}: Rule 186 frame must start with r186_")
        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 186")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied landform/place/use/old-field 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 retained Rule 185 target head, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected.replace(" ", ".") not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yinyay") or "yinyay" not in words or "there" not in english_low:
                issues.append(f"{label}: Rule 186 deictic rows require yinyay/there")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 186 perception rows must use nyaji-l")
            first = first_word(low)
            if first not in PRONOUN_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun")
            if 11 <= seq <= 20 and (first != "ngayu" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 11-20 require ngayu + yaluy/here")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yaluy/here")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yaluy") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yaluy + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yinyay/there")
            if "nyajin" in low and "see-PAST" not in analysis:
                issues.append(f"{label}: nyajin must be glossed as see-PAST")
            if "nyajil" in low and "see-NONPAST" not in analysis:
                issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied route/water/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 186 draft: construction consolidation after Rule 185", "operator-guide-2026-07-08", "under_review", NOW),
        )
        batch_id = cur.lastrowid

    dupes: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        hit = db.execute(
            """
            SELECT b.label, s.seq
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(trim(s.kuku))=lower(trim(?))
              AND s.status!='rejected'
              AND s.batch_id!=?
            """,
            (kuku, batch_id),
        ).fetchone()
        if hit:
            dupes.append(f"{LABEL}.{seq:02d} duplicates {hit[0]}.{hit[1]:02d}: {kuku}")
    if dupes:
        db.rollback()
        print("cross-corpus duplicate check failed:")
        for dupe in dupes:
            print(f"  - {dupe}")
        return 1

    record_event(db, batch_label=LABEL, phase="source", event_type="source-pass", actor="claude-main",
                 detail="Rule 186 source pass retained exactly the ten Rule 185 landform/geography reference heads: binda-dijarr, duli, jamar, kabay, karrangkal, kuri, ngamar, nganyay, ngidin, and warrmba. Fresh dictionary readback reconfirmed selected senses and traps: binda-dijarr common stony crossing versus capitalized place-name/river-crossing risk; duli lexical burnt patch with no burning event; jamar lexical newly cleared scrub with no clearing action; kabay small ant bed with no ant/insect behavior; karrangkal reef not coral/sea/water; kuri small scrub patch only; ngamar cliff not climbing/danger; nganyay desert not heat/travel/scarcity; ngidin boundary not ownership/dispute; warrmba place noun, not -bungal find/peep verb. Rejected candidates stay closed. Patz readback reconfirmed yaluy/yinyay, nyaji-l/nyaji-ny, absolutive bare objects, and bare pronoun A forms.",
                 command="structured dictionary YAML readback; rg grammar readback; sqlite corpus readback",
                 artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="scope", event_type="construction-scope", actor="claude-main",
                 detail="Rule 186 is a landform-reference construction consolidation pass for the Rule 185 field. It admits no new target heads and excludes place names, rejected landform candidates, route/travel/crossing-event, river/water-use, burning, clearing, live ant/insect behavior, ecology, coral/sea/collecting/habitat, climbing/falling/danger, heat/scarcity, ownership/dispute/legal/social, finding/peeping, causative, dialect-variant, rubbish/debris/beach-wrack/leaf-mould/growing-use, target case, target compounds, plural derivation, productive reduplication, and event claims.",
                 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 found 50 planned Kuku surfaces, 50 unique within-batch surfaces, and no exact accepted/revised/under_review cross-corpus duplicates.",
                 command="sqlite exact lower(trim(kuku)) duplicate scan before banking", artifact_path="batch_scripts/bank_228.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: all 50 rows have exactly one retained Rule 185 target, no loans, no denied Kuku tokens, no denied English import fields, no target case/compound morphology, required deictic/perception support, bare pronoun A where applicable, and correct nyajil/nyajin glosses.",
                 command="python3 batch_scripts/bank_228.py internal scan_static()", artifact_path="batch_scripts/bank_228.py", created_at=NOW)

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [(batch_id, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()
    count = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'", (batch_id,)).fetchone()[0]
    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    print(f"banked {LABEL}: rows={len(ROWS)}, under_review={count}, verified_before_close={verified}")
    return 0


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