#!/usr/bin/env python3
"""Bank batch-227: Rule 185 landform reference lexical expansion after Rule 184."""

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-227"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-227-landform-reference-lexical-expansion-after-rule184-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 = {
    "baral", "bubu", "damu", "naka", "jalkar", "jalkaraburr", "jalngarr", "jangka", "janku",
    "kambal-kambal", "kambar", "kangku", "karrirrangkal", "kulji", "kurrkal", "mabil",
    "madja", "manjal", "ngunnga", "nurru", "nyamun", "walba-murru", "yikin", "ngunnga-bungal", "warrmba-bungal",
    "biyin", "gilaja", "binjin", "julnji", "nyumbirr", "wawu-juljal",
}
DENY_ENGLISH = (
    "place-name", "butcher", "river", "water", "road", "path", "track", "trail", "travel", "walk", "walking",
    "go", "went", "route", "shortcut", "south", "slope", "person facing", "ants", "insect", "corroboree",
    "ancestral", "home out west", "special dance", "no definition", "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",
)


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 here.", "Binda-dijarr yaluy.", "binda-dijarr yaluy | stony.crossing here", "r185_deictic_binda_dijarr_here", ["binda-dijarr", "yaluy"], "Rule 185 admits binda-dijarr as stony crossing; capitalized place-name and route/river event senses closed."),
    row(2, "The burnt patch of grass is here.", "Duli yaluy.", "duli yaluy | burnt.patch.of.grass here", "r185_deictic_duli_here", ["duli", "yaluy"], "Rule 185 admits duli as burnt patch of grass; no fire/burning event row."),
    row(3, "The newly cleared scrub is here.", "Jamar yaluy.", "jamar yaluy | newly.cleared.scrub here", "r185_deictic_jamar_here", ["jamar", "yaluy"], "Rule 185 admits jamar as newly cleared scrub; no clearing action row."),
    row(4, "The small ant bed is here.", "Kabay yaluy.", "kabay yaluy | small.ant.bed here", "r185_deictic_kabay_here", ["kabay", "yaluy"], "Rule 185 admits kabay as small ant bed; no ant/insect behavior row."),
    row(5, "The reef is here.", "Karrangkal yaluy.", "karrangkal yaluy | reef here", "r185_deictic_karrangkal_here", ["karrangkal", "yaluy"], "Rule 185 admits karrangkal as reef; coral/sea/water claims closed."),
    row(6, "The small patch of scrub is here.", "Kuri yaluy.", "kuri yaluy | small.patch.of.scrub here", "r185_deictic_kuri_here", ["kuri", "yaluy"], "Rule 185 admits kuri as small patch of scrub; no plant-use/ecology row."),
    row(7, "The cliff is here.", "Ngamar yaluy.", "ngamar yaluy | cliff here", "r185_deictic_ngamar_here", ["ngamar", "yaluy"], "Rule 185 admits ngamar as cliff; no climbing/danger row."),
    row(8, "The desert is here.", "Nganyay yaluy.", "nganyay yaluy | desert here", "r185_deictic_nganyay_here", ["nganyay", "yaluy"], "Rule 185 admits nganyay as desert; no heat/travel/scarcity row."),
    row(9, "The boundary is here.", "Ngidin yaluy.", "ngidin yaluy | boundary here", "r185_deictic_ngidin_here", ["ngidin", "yaluy"], "Rule 185 admits ngidin as boundary; no ownership/dispute row."),
    row(10, "The exposed place is here.", "Warrmba yaluy.", "warrmba yaluy | exposed.place here", "r185_deictic_warrmba_here", ["warrmba", "yaluy"], "Rule 185 admits warrmba as exposed place; no causative/find/peep row."),
    row(11, "I see the stony crossing.", "Ngayu binda-dijarr nyajil.", "ngayu binda-dijarr nyaji-l | I stony.crossing see-NONPAST", "r185_present_i_binda_dijarr", ["ngayu", "binda-dijarr", "nyaji-l"], "First-person present perception; target landform bare."),
    row(12, "I see the burnt patch of grass.", "Ngayu duli nyajil.", "ngayu duli nyaji-l | I burnt.patch.of.grass see-NONPAST", "r185_present_i_duli", ["ngayu", "duli", "nyaji-l"], "First-person present perception; no fire/burning event row."),
    row(13, "I see the newly cleared scrub.", "Ngayu jamar nyajil.", "ngayu jamar nyaji-l | I newly.cleared.scrub see-NONPAST", "r185_present_i_jamar", ["ngayu", "jamar", "nyaji-l"], "First-person present perception; no clearing action row."),
    row(14, "I see the small ant bed.", "Ngayu kabay nyajil.", "ngayu kabay nyaji-l | I small.ant.bed see-NONPAST", "r185_present_i_kabay", ["ngayu", "kabay", "nyaji-l"], "First-person present perception; no ant/insect behavior row."),
    row(15, "I see the reef.", "Ngayu karrangkal nyajil.", "ngayu karrangkal nyaji-l | I reef see-NONPAST", "r185_present_i_karrangkal", ["ngayu", "karrangkal", "nyaji-l"], "First-person present perception; coral/sea/water claims closed."),
    row(16, "I see the small patch of scrub.", "Ngayu kuri nyajil.", "ngayu kuri nyaji-l | I small.patch.of.scrub see-NONPAST", "r185_present_i_kuri", ["ngayu", "kuri", "nyaji-l"], "First-person present perception; plant-use/ecology closed."),
    row(17, "I see the cliff.", "Ngayu ngamar nyajil.", "ngayu ngamar nyaji-l | I cliff see-NONPAST", "r185_present_i_ngamar", ["ngayu", "ngamar", "nyaji-l"], "First-person present perception; no climbing/danger row."),
    row(18, "I see the desert.", "Ngayu nganyay nyajil.", "ngayu nganyay nyaji-l | I desert see-NONPAST", "r185_present_i_nganyay", ["ngayu", "nganyay", "nyaji-l"], "First-person present perception; no heat/travel/scarcity row."),
    row(19, "I see the boundary.", "Ngayu ngidin nyajil.", "ngayu ngidin nyaji-l | I boundary see-NONPAST", "r185_present_i_ngidin", ["ngayu", "ngidin", "nyaji-l"], "First-person present perception; no ownership/dispute row."),
    row(20, "I see the exposed place.", "Ngayu warrmba nyajil.", "ngayu warrmba nyaji-l | I exposed.place see-NONPAST", "r185_present_i_warrmba", ["ngayu", "warrmba", "nyaji-l"], "First-person present perception; no warrmba-bungal verb row."),
    row(21, "You see the stony crossing there.", "Yundu binda-dijarr yinyay nyajil.", "yundu binda-dijarr yinyay nyaji-l | you stony.crossing there see-NONPAST", "r185_present_you_binda_dijarr_there", ["yundu", "binda-dijarr", "yinyay", "nyaji-l"], "Second-person present perception with yinyay support."),
    row(22, "You see the burnt patch of grass there.", "Yundu duli yinyay nyajil.", "yundu duli yinyay nyaji-l | you burnt.patch.of.grass there see-NONPAST", "r185_present_you_duli_there", ["yundu", "duli", "yinyay", "nyaji-l"], "Second-person present perception; no fire/burning event row."),
    row(23, "You see the newly cleared scrub there.", "Yundu jamar yinyay nyajil.", "yundu jamar yinyay nyaji-l | you newly.cleared.scrub there see-NONPAST", "r185_present_you_jamar_there", ["yundu", "jamar", "yinyay", "nyaji-l"], "Second-person present perception; no clearing action row."),
    row(24, "You see the small ant bed there.", "Yundu kabay yinyay nyajil.", "yundu kabay yinyay nyaji-l | you small.ant.bed there see-NONPAST", "r185_present_you_kabay_there", ["yundu", "kabay", "yinyay", "nyaji-l"], "Second-person present perception; no ant/insect behavior row."),
    row(25, "You see the reef there.", "Yundu karrangkal yinyay nyajil.", "yundu karrangkal yinyay nyaji-l | you reef there see-NONPAST", "r185_present_you_karrangkal_there", ["yundu", "karrangkal", "yinyay", "nyaji-l"], "Second-person present perception; reef only."),
    row(26, "You see the small patch of scrub there.", "Yundu kuri yinyay nyajil.", "yundu kuri yinyay nyaji-l | you small.patch.of.scrub there see-NONPAST", "r185_present_you_kuri_there", ["yundu", "kuri", "yinyay", "nyaji-l"], "Second-person present perception; plant-use/ecology closed."),
    row(27, "You see the cliff there.", "Yundu ngamar yinyay nyajil.", "yundu ngamar yinyay nyaji-l | you cliff there see-NONPAST", "r185_present_you_ngamar_there", ["yundu", "ngamar", "yinyay", "nyaji-l"], "Second-person present perception; no climbing/danger row."),
    row(28, "You see the desert there.", "Yundu nganyay yinyay nyajil.", "yundu nganyay yinyay nyaji-l | you desert there see-NONPAST", "r185_present_you_nganyay_there", ["yundu", "nganyay", "yinyay", "nyaji-l"], "Second-person present perception; desert only."),
    row(29, "You see the boundary there.", "Yundu ngidin yinyay nyajil.", "yundu ngidin yinyay nyaji-l | you boundary there see-NONPAST", "r185_present_you_ngidin_there", ["yundu", "ngidin", "yinyay", "nyaji-l"], "Second-person present perception; no dispute/legal row."),
    row(30, "You see the exposed place there.", "Yundu warrmba yinyay nyajil.", "yundu warrmba yinyay nyaji-l | you exposed.place there see-NONPAST", "r185_present_you_warrmba_there", ["yundu", "warrmba", "yinyay", "nyaji-l"], "Second-person present perception; no causative/find/peep row."),
    row(31, "They saw the stony crossing there.", "Jana binda-dijarr yinyay nyajin.", "jana binda-dijarr yinyay nyaji-ny | they stony.crossing there see-PAST", "r185_past_they_binda_dijarr_there", ["jana", "binda-dijarr", "yinyay", "nyaji-l"], "Third-person plural past perception with yinyay support."),
    row(32, "They saw the burnt patch of grass there.", "Jana duli yinyay nyajin.", "jana duli yinyay nyaji-ny | they burnt.patch.of.grass there see-PAST", "r185_past_they_duli_there", ["jana", "duli", "yinyay", "nyaji-l"], "Third-person plural past perception; no fire/burning event row."),
    row(33, "They saw the newly cleared scrub there.", "Jana jamar yinyay nyajin.", "jana jamar yinyay nyaji-ny | they newly.cleared.scrub there see-PAST", "r185_past_they_jamar_there", ["jana", "jamar", "yinyay", "nyaji-l"], "Third-person plural past perception; no clearing action row."),
    row(34, "They saw the small ant bed there.", "Jana kabay yinyay nyajin.", "jana kabay yinyay nyaji-ny | they small.ant.bed there see-PAST", "r185_past_they_kabay_there", ["jana", "kabay", "yinyay", "nyaji-l"], "Third-person plural past perception; no ant/insect behavior row."),
    row(35, "They saw the reef there.", "Jana karrangkal yinyay nyajin.", "jana karrangkal yinyay nyaji-ny | they reef there see-PAST", "r185_past_they_karrangkal_there", ["jana", "karrangkal", "yinyay", "nyaji-l"], "Third-person plural past perception; reef only."),
    row(36, "They saw the small patch of scrub there.", "Jana kuri yinyay nyajin.", "jana kuri yinyay nyaji-ny | they small.patch.of.scrub there see-PAST", "r185_past_they_kuri_there", ["jana", "kuri", "yinyay", "nyaji-l"], "Third-person plural past perception; plant-use/ecology closed."),
    row(37, "They saw the cliff there.", "Jana ngamar yinyay nyajin.", "jana ngamar yinyay nyaji-ny | they cliff there see-PAST", "r185_past_they_ngamar_there", ["jana", "ngamar", "yinyay", "nyaji-l"], "Third-person plural past perception; no climbing/danger row."),
    row(38, "They saw the desert there.", "Jana nganyay yinyay nyajin.", "jana nganyay yinyay nyaji-ny | they desert there see-PAST", "r185_past_they_nganyay_there", ["jana", "nganyay", "yinyay", "nyaji-l"], "Third-person plural past perception; desert only."),
    row(39, "They saw the boundary there.", "Jana ngidin yinyay nyajin.", "jana ngidin yinyay nyaji-ny | they boundary there see-PAST", "r185_past_they_ngidin_there", ["jana", "ngidin", "yinyay", "nyaji-l"], "Third-person plural past perception; no dispute/legal row."),
    row(40, "They saw the exposed place there.", "Jana warrmba yinyay nyajin.", "jana warrmba yinyay nyaji-ny | they exposed.place there see-PAST", "r185_past_they_warrmba_there", ["jana", "warrmba", "yinyay", "nyaji-l"], "Third-person plural past perception; no causative/find/peep row."),
    row(41, "We see the stony crossing here.", "Ngana binda-dijarr yaluy nyajil.", "ngana binda-dijarr yaluy nyaji-l | we stony.crossing here see-NONPAST", "r185_present_we_binda_dijarr_here", ["ngana", "binda-dijarr", "yaluy", "nyaji-l"], "Inclusive present perception with yaluy support."),
    row(42, "We see the burnt patch of grass here.", "Ngana duli yaluy nyajil.", "ngana duli yaluy nyaji-l | we burnt.patch.of.grass here see-NONPAST", "r185_present_we_duli_here", ["ngana", "duli", "yaluy", "nyaji-l"], "Inclusive present perception; no fire/burning event row."),
    row(43, "We see the newly cleared scrub here.", "Ngana jamar yaluy nyajil.", "ngana jamar yaluy nyaji-l | we newly.cleared.scrub here see-NONPAST", "r185_present_we_jamar_here", ["ngana", "jamar", "yaluy", "nyaji-l"], "Inclusive present perception; no clearing action row."),
    row(44, "We see the small ant bed here.", "Ngana kabay yaluy nyajil.", "ngana kabay yaluy nyaji-l | we small.ant.bed here see-NONPAST", "r185_present_we_kabay_here", ["ngana", "kabay", "yaluy", "nyaji-l"], "Inclusive present perception; no ant/insect behavior row."),
    row(45, "We see the reef here.", "Ngana karrangkal yaluy nyajil.", "ngana karrangkal yaluy nyaji-l | we reef here see-NONPAST", "r185_present_we_karrangkal_here", ["ngana", "karrangkal", "yaluy", "nyaji-l"], "Inclusive present perception; reef only."),
    row(46, "We see the small patch of scrub here.", "Ngana kuri yaluy nyajil.", "ngana kuri yaluy nyaji-l | we small.patch.of.scrub here see-NONPAST", "r185_present_we_kuri_here", ["ngana", "kuri", "yaluy", "nyaji-l"], "Inclusive present perception; plant-use/ecology closed."),
    row(47, "We see the cliff here.", "Ngana ngamar yaluy nyajil.", "ngana ngamar yaluy nyaji-l | we cliff here see-NONPAST", "r185_present_we_ngamar_here", ["ngana", "ngamar", "yaluy", "nyaji-l"], "Inclusive present perception; no climbing/danger row."),
    row(48, "We see the desert here.", "Ngana nganyay yaluy nyajil.", "ngana nganyay yaluy nyaji-l | we desert here see-NONPAST", "r185_present_we_nganyay_here", ["ngana", "nganyay", "yaluy", "nyaji-l"], "Inclusive present perception; desert only."),
    row(49, "We see the boundary here.", "Ngana ngidin yaluy nyajil.", "ngana ngidin yaluy nyaji-l | we boundary here see-NONPAST", "r185_present_we_ngidin_here", ["ngana", "ngidin", "yaluy", "nyaji-l"], "Inclusive present perception; no dispute/legal row."),
    row(50, "We see the exposed place here.", "Ngana warrmba yaluy nyajil.", "ngana warrmba yaluy nyaji-l | we exposed.place here see-NONPAST", "r185_present_we_warrmba_here", ["ngana", "warrmba", "yaluy", "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("r185_"):
            issues.append(f"{label}: Rule 185 frame must start with r185_")
        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 185")
        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 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, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 185 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 185 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":
                issues.append(f"{label}: rows 11-20 require ngayu")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            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 185 draft: landform reference lexical expansion after Rule 184", "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 185 source pass selected ten zero-hit landform/geography reference heads: binda-dijarr, duli, jamar, kabay, karrangkal, kuri, ngamar, nganyay, ngidin, and warrmba. Fresh dictionary readback confirmed 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 damu naka, kurrkal, ngunnga, nurru, nyamun, walba-murru, and yikin. 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 exact zero-hit corpus readback",
                 artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="scope", event_type="lexical-scope", actor="claude-main",
                 detail="Rule 185 is a landform-reference lexical pass for ten bare target heads. It 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_227.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one Rule 185 landform target per row; all targets bare; no loans; no rejected landform/place-name/route/water/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_227.py static scan", artifact_path="batch_scripts/bank_227.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()

    under_review = 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={under_review}, verified_before_close={verified}")
    return 0


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