#!/usr/bin/env python3
"""Bank batch-275: Rule 233 landform/geography construction consolidation."""

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

TARGET_HEADS = {
    "mabil": "swamp",
    "karrirrangkal": "coral",
    "jalngarr": "flat rock",
    "jinali": "smooth rock",
    "kangku": "valley",
    "yalmba": "seashore",
    "kambal-kambal": "mud",
    "jalkar": "high bank",
    "janku": "hole",
    "jamba": "hillside",
}
SUPPORT = {"yinya", "yaluy", "yinyay", "yundu", "nyulu", "ngana", "jana", "nyajil", "nyajin"}
DENY_KUKU = {
    # Rule 185-186 landform targets and rejected/high-risk candidates.
    "binda-dijarr", "duli", "jamar", "kabay", "karrangkal", "kuri", "ngamar", "nganyay",
    "ngidin", "warrmba", "damu naka", "kurrkal", "ngunnga", "nurru", "nyamun", "walba-murru",
    "yikin", "jalkaraburr", "manjal",
    # High-frequency geography/object heads deliberately not part of Rule 233.
    "bubu", "baral", "kulji", "jukar", "madja", "wabarr",
    # This batch changes away from the Rule 232 1sg band.
    "ngayu",
}
DENY_ENGLISH = (
    "route", "travel", "cross", "crossing", "river", "water", "waterhole", "burn", "burning",
    "clear", "clearing", "cleared", "ant", "insect", "reef", "sea", "lime", "collect",
    "gather", "habitat", "ecology", "climb", "fall", "danger", "scarcity", "ownership",
    "dispute", "legal", "social", "find", "peep", "cause", "rubbish", "debris", "leaf",
    "mould", "grow", "growing", "road", "path", "track", "shortcut", "place name", "story",
    "country", "pass", "trail", "beach collect", "tide",
)


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")


EVIDENCE = {
    "mabil": "Dictionary mabil noun gloss 'swamp'. Rule 233 carries forward Rule 232 bare landform reference only. Patz 3.5 sources yundu/nyulu/ngana/jana nominative pronouns; Patz 3.7 sources yinya/yaluy/yinyay; Patz text example supports nyaji-l nonpast and corpus convention supports nyajin past.",
    "karrirrangkal": "Dictionary karrirrangkal noun gloss 'coral' with definition 'coral crushed for lime'. Rule 233 keeps coral reference only; lime/use prose stays closed. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "jalngarr": "Dictionary jalngarr noun gloss 'flat rock'. Rule 233 uses bare flat-rock reference only. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "jinali": "Dictionary jinali noun gloss 'smooth rock'. Rule 233 keeps the whole noun sense and does not open smooth-property predication. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "kangku": "Dictionary kangku noun gloss 'valley' with definition 'low gap in mountain, mountain pass'. Rule 233 uses valley reference only; route/pass prose stays closed. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "yalmba": "Dictionary yalmba noun gloss 'seashore' with definition 'seashore, beach'. Rule 233 uses seashore reference only. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "kambal-kambal": "Dictionary kambal-kambal noun gloss 'mud', lexicalized reduplicated form. Rule 233 uses the whole headword as a noun only. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "jalkar": "Dictionary jalkar noun gloss 'high bank'. Commentary contrasts jalkar-jalkar 'steep', which remains closed. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "janku": "Dictionary janku noun gloss 'hole' with definition 'hole in the ground'. Rule 233 uses hole reference only. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
    "jamba": "Dictionary jamba noun gloss 'hillside'. Rule 233 uses hillside reference only. Patz 3.5, 3.7, and nyaji-l/nyajin perception support.",
}


ROWS = [
    row(1, "That swamp is here.", "Mabil yinya yaluy.", "mabil yinya yaluy | swamp that here", "r233_postposed_that_here_mabil", ["mabil", "yinya", "yaluy"], EVIDENCE["mabil"]),
    row(2, "That coral is here.", "Karrirrangkal yinya yaluy.", "karrirrangkal yinya yaluy | coral that here", "r233_postposed_that_here_karrirrangkal", ["karrirrangkal", "yinya", "yaluy"], EVIDENCE["karrirrangkal"]),
    row(3, "That flat rock is here.", "Jalngarr yinya yaluy.", "jalngarr yinya yaluy | flat.rock that here", "r233_postposed_that_here_jalngarr", ["jalngarr", "yinya", "yaluy"], EVIDENCE["jalngarr"]),
    row(4, "That smooth rock is here.", "Jinali yinya yaluy.", "jinali yinya yaluy | smooth.rock that here", "r233_postposed_that_here_jinali", ["jinali", "yinya", "yaluy"], EVIDENCE["jinali"]),
    row(5, "That valley is here.", "Kangku yinya yaluy.", "kangku yinya yaluy | valley that here", "r233_postposed_that_here_kangku", ["kangku", "yinya", "yaluy"], EVIDENCE["kangku"]),
    row(6, "That seashore is here.", "Yalmba yinya yaluy.", "yalmba yinya yaluy | seashore that here", "r233_postposed_that_here_yalmba", ["yalmba", "yinya", "yaluy"], EVIDENCE["yalmba"]),
    row(7, "That mud is here.", "Kambal-kambal yinya yaluy.", "kambal-kambal yinya yaluy | mud that here", "r233_postposed_that_here_kambal_kambal", ["kambal-kambal", "yinya", "yaluy"], EVIDENCE["kambal-kambal"]),
    row(8, "That high bank is here.", "Jalkar yinya yaluy.", "jalkar yinya yaluy | high.bank that here", "r233_postposed_that_here_jalkar", ["jalkar", "yinya", "yaluy"], EVIDENCE["jalkar"]),
    row(9, "That hole is here.", "Janku yinya yaluy.", "janku yinya yaluy | hole that here", "r233_postposed_that_here_janku", ["janku", "yinya", "yaluy"], EVIDENCE["janku"]),
    row(10, "That hillside is here.", "Jamba yinya yaluy.", "jamba yinya yaluy | hillside that here", "r233_postposed_that_here_jamba", ["jamba", "yinya", "yaluy"], EVIDENCE["jamba"]),
    row(11, "You see the swamp there.", "Yundu mabil yinyay nyajil.", "yundu mabil yinyay nyajil | 2sg swamp there perceive.NONPAST", "r233_2sg_landform_there_mabil", ["yundu", "mabil", "yinyay", "nyajil"], EVIDENCE["mabil"]),
    row(12, "You see the coral there.", "Yundu karrirrangkal yinyay nyajil.", "yundu karrirrangkal yinyay nyajil | 2sg coral there perceive.NONPAST", "r233_2sg_landform_there_karrirrangkal", ["yundu", "karrirrangkal", "yinyay", "nyajil"], EVIDENCE["karrirrangkal"]),
    row(13, "You see the flat rock there.", "Yundu jalngarr yinyay nyajil.", "yundu jalngarr yinyay nyajil | 2sg flat.rock there perceive.NONPAST", "r233_2sg_landform_there_jalngarr", ["yundu", "jalngarr", "yinyay", "nyajil"], EVIDENCE["jalngarr"]),
    row(14, "You see the smooth rock there.", "Yundu jinali yinyay nyajil.", "yundu jinali yinyay nyajil | 2sg smooth.rock there perceive.NONPAST", "r233_2sg_landform_there_jinali", ["yundu", "jinali", "yinyay", "nyajil"], EVIDENCE["jinali"]),
    row(15, "You see the valley there.", "Yundu kangku yinyay nyajil.", "yundu kangku yinyay nyajil | 2sg valley there perceive.NONPAST", "r233_2sg_landform_there_kangku", ["yundu", "kangku", "yinyay", "nyajil"], EVIDENCE["kangku"]),
    row(16, "You see the seashore there.", "Yundu yalmba yinyay nyajil.", "yundu yalmba yinyay nyajil | 2sg seashore there perceive.NONPAST", "r233_2sg_landform_there_yalmba", ["yundu", "yalmba", "yinyay", "nyajil"], EVIDENCE["yalmba"]),
    row(17, "You see the mud there.", "Yundu kambal-kambal yinyay nyajil.", "yundu kambal-kambal yinyay nyajil | 2sg mud there perceive.NONPAST", "r233_2sg_landform_there_kambal_kambal", ["yundu", "kambal-kambal", "yinyay", "nyajil"], EVIDENCE["kambal-kambal"]),
    row(18, "You see the high bank there.", "Yundu jalkar yinyay nyajil.", "yundu jalkar yinyay nyajil | 2sg high.bank there perceive.NONPAST", "r233_2sg_landform_there_jalkar", ["yundu", "jalkar", "yinyay", "nyajil"], EVIDENCE["jalkar"]),
    row(19, "You see the hole there.", "Yundu janku yinyay nyajil.", "yundu janku yinyay nyajil | 2sg hole there perceive.NONPAST", "r233_2sg_landform_there_janku", ["yundu", "janku", "yinyay", "nyajil"], EVIDENCE["janku"]),
    row(20, "You see the hillside there.", "Yundu jamba yinyay nyajil.", "yundu jamba yinyay nyajil | 2sg hillside there perceive.NONPAST", "r233_2sg_landform_there_jamba", ["yundu", "jamba", "yinyay", "nyajil"], EVIDENCE["jamba"]),
    row(21, "He sees the swamp here.", "Nyulu mabil yaluy nyajil.", "nyulu mabil yaluy nyajil | 3sg swamp here perceive.NONPAST", "r233_3sg_landform_here_mabil", ["nyulu", "mabil", "yaluy", "nyajil"], EVIDENCE["mabil"]),
    row(22, "He sees the coral here.", "Nyulu karrirrangkal yaluy nyajil.", "nyulu karrirrangkal yaluy nyajil | 3sg coral here perceive.NONPAST", "r233_3sg_landform_here_karrirrangkal", ["nyulu", "karrirrangkal", "yaluy", "nyajil"], EVIDENCE["karrirrangkal"]),
    row(23, "He sees the flat rock here.", "Nyulu jalngarr yaluy nyajil.", "nyulu jalngarr yaluy nyajil | 3sg flat.rock here perceive.NONPAST", "r233_3sg_landform_here_jalngarr", ["nyulu", "jalngarr", "yaluy", "nyajil"], EVIDENCE["jalngarr"]),
    row(24, "He sees the smooth rock here.", "Nyulu jinali yaluy nyajil.", "nyulu jinali yaluy nyajil | 3sg smooth.rock here perceive.NONPAST", "r233_3sg_landform_here_jinali", ["nyulu", "jinali", "yaluy", "nyajil"], EVIDENCE["jinali"]),
    row(25, "He sees the valley here.", "Nyulu kangku yaluy nyajil.", "nyulu kangku yaluy nyajil | 3sg valley here perceive.NONPAST", "r233_3sg_landform_here_kangku", ["nyulu", "kangku", "yaluy", "nyajil"], EVIDENCE["kangku"]),
    row(26, "He sees the seashore here.", "Nyulu yalmba yaluy nyajil.", "nyulu yalmba yaluy nyajil | 3sg seashore here perceive.NONPAST", "r233_3sg_landform_here_yalmba", ["nyulu", "yalmba", "yaluy", "nyajil"], EVIDENCE["yalmba"]),
    row(27, "He sees the mud here.", "Nyulu kambal-kambal yaluy nyajil.", "nyulu kambal-kambal yaluy nyajil | 3sg mud here perceive.NONPAST", "r233_3sg_landform_here_kambal_kambal", ["nyulu", "kambal-kambal", "yaluy", "nyajil"], EVIDENCE["kambal-kambal"]),
    row(28, "He sees the high bank here.", "Nyulu jalkar yaluy nyajil.", "nyulu jalkar yaluy nyajil | 3sg high.bank here perceive.NONPAST", "r233_3sg_landform_here_jalkar", ["nyulu", "jalkar", "yaluy", "nyajil"], EVIDENCE["jalkar"]),
    row(29, "He sees the hole here.", "Nyulu janku yaluy nyajil.", "nyulu janku yaluy nyajil | 3sg hole here perceive.NONPAST", "r233_3sg_landform_here_janku", ["nyulu", "janku", "yaluy", "nyajil"], EVIDENCE["janku"]),
    row(30, "He sees the hillside here.", "Nyulu jamba yaluy nyajil.", "nyulu jamba yaluy nyajil | 3sg hillside here perceive.NONPAST", "r233_3sg_landform_here_jamba", ["nyulu", "jamba", "yaluy", "nyajil"], EVIDENCE["jamba"]),
    row(31, "We see the swamp there.", "Ngana mabil yinyay nyajil.", "ngana mabil yinyay nyajil | 1pl.incl swamp there perceive.NONPAST", "r233_1pl_incl_landform_there_mabil", ["ngana", "mabil", "yinyay", "nyajil"], EVIDENCE["mabil"]),
    row(32, "We see the coral there.", "Ngana karrirrangkal yinyay nyajil.", "ngana karrirrangkal yinyay nyajil | 1pl.incl coral there perceive.NONPAST", "r233_1pl_incl_landform_there_karrirrangkal", ["ngana", "karrirrangkal", "yinyay", "nyajil"], EVIDENCE["karrirrangkal"]),
    row(33, "We see the flat rock there.", "Ngana jalngarr yinyay nyajil.", "ngana jalngarr yinyay nyajil | 1pl.incl flat.rock there perceive.NONPAST", "r233_1pl_incl_landform_there_jalngarr", ["ngana", "jalngarr", "yinyay", "nyajil"], EVIDENCE["jalngarr"]),
    row(34, "We see the smooth rock there.", "Ngana jinali yinyay nyajil.", "ngana jinali yinyay nyajil | 1pl.incl smooth.rock there perceive.NONPAST", "r233_1pl_incl_landform_there_jinali", ["ngana", "jinali", "yinyay", "nyajil"], EVIDENCE["jinali"]),
    row(35, "We see the valley there.", "Ngana kangku yinyay nyajil.", "ngana kangku yinyay nyajil | 1pl.incl valley there perceive.NONPAST", "r233_1pl_incl_landform_there_kangku", ["ngana", "kangku", "yinyay", "nyajil"], EVIDENCE["kangku"]),
    row(36, "We see the seashore there.", "Ngana yalmba yinyay nyajil.", "ngana yalmba yinyay nyajil | 1pl.incl seashore there perceive.NONPAST", "r233_1pl_incl_landform_there_yalmba", ["ngana", "yalmba", "yinyay", "nyajil"], EVIDENCE["yalmba"]),
    row(37, "We see the mud there.", "Ngana kambal-kambal yinyay nyajil.", "ngana kambal-kambal yinyay nyajil | 1pl.incl mud there perceive.NONPAST", "r233_1pl_incl_landform_there_kambal_kambal", ["ngana", "kambal-kambal", "yinyay", "nyajil"], EVIDENCE["kambal-kambal"]),
    row(38, "We see the high bank there.", "Ngana jalkar yinyay nyajil.", "ngana jalkar yinyay nyajil | 1pl.incl high.bank there perceive.NONPAST", "r233_1pl_incl_landform_there_jalkar", ["ngana", "jalkar", "yinyay", "nyajil"], EVIDENCE["jalkar"]),
    row(39, "We see the hole there.", "Ngana janku yinyay nyajil.", "ngana janku yinyay nyajil | 1pl.incl hole there perceive.NONPAST", "r233_1pl_incl_landform_there_janku", ["ngana", "janku", "yinyay", "nyajil"], EVIDENCE["janku"]),
    row(40, "We see the hillside there.", "Ngana jamba yinyay nyajil.", "ngana jamba yinyay nyajil | 1pl.incl hillside there perceive.NONPAST", "r233_1pl_incl_landform_there_jamba", ["ngana", "jamba", "yinyay", "nyajil"], EVIDENCE["jamba"]),
    row(41, "They saw the swamp here.", "Jana mabil yaluy nyajin.", "jana mabil yaluy nyajin | 3pl swamp here perceive.PAST", "r233_3pl_landform_here_past_mabil", ["jana", "mabil", "yaluy", "nyajin"], EVIDENCE["mabil"]),
    row(42, "They saw the coral here.", "Jana karrirrangkal yaluy nyajin.", "jana karrirrangkal yaluy nyajin | 3pl coral here perceive.PAST", "r233_3pl_landform_here_past_karrirrangkal", ["jana", "karrirrangkal", "yaluy", "nyajin"], EVIDENCE["karrirrangkal"]),
    row(43, "They saw the flat rock here.", "Jana jalngarr yaluy nyajin.", "jana jalngarr yaluy nyajin | 3pl flat.rock here perceive.PAST", "r233_3pl_landform_here_past_jalngarr", ["jana", "jalngarr", "yaluy", "nyajin"], EVIDENCE["jalngarr"]),
    row(44, "They saw the smooth rock here.", "Jana jinali yaluy nyajin.", "jana jinali yaluy nyajin | 3pl smooth.rock here perceive.PAST", "r233_3pl_landform_here_past_jinali", ["jana", "jinali", "yaluy", "nyajin"], EVIDENCE["jinali"]),
    row(45, "They saw the valley here.", "Jana kangku yaluy nyajin.", "jana kangku yaluy nyajin | 3pl valley here perceive.PAST", "r233_3pl_landform_here_past_kangku", ["jana", "kangku", "yaluy", "nyajin"], EVIDENCE["kangku"]),
    row(46, "They saw the seashore here.", "Jana yalmba yaluy nyajin.", "jana yalmba yaluy nyajin | 3pl seashore here perceive.PAST", "r233_3pl_landform_here_past_yalmba", ["jana", "yalmba", "yaluy", "nyajin"], EVIDENCE["yalmba"]),
    row(47, "They saw the mud here.", "Jana kambal-kambal yaluy nyajin.", "jana kambal-kambal yaluy nyajin | 3pl mud here perceive.PAST", "r233_3pl_landform_here_past_kambal_kambal", ["jana", "kambal-kambal", "yaluy", "nyajin"], EVIDENCE["kambal-kambal"]),
    row(48, "They saw the high bank here.", "Jana jalkar yaluy nyajin.", "jana jalkar yaluy nyajin | 3pl high.bank here perceive.PAST", "r233_3pl_landform_here_past_jalkar", ["jana", "jalkar", "yaluy", "nyajin"], EVIDENCE["jalkar"]),
    row(49, "They saw the hole here.", "Jana janku yaluy nyajin.", "jana janku yaluy nyajin | 3pl hole here perceive.PAST", "r233_3pl_landform_here_past_janku", ["jana", "janku", "yaluy", "nyajin"], EVIDENCE["janku"]),
    row(50, "They saw the hillside here.", "Jana jamba yaluy nyajin.", "jana jamba yaluy nyajin | 3pl hillside here perceive.PAST", "r233_3pl_landform_here_past_jamba", ["jana", "jamba", "yaluy", "nyajin"], EVIDENCE["jamba"]),
]


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|karra|manda|bulal"
    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("r233_"):
            issues.append(f"{label}: Rule 233 frame must start with r233_")
        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 233")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied landform/geography or 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 233 target noun, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            dotted = selected.replace("-", ".").replace(" ", ".")
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected not in analysis and dotted not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        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 (
            low.startswith("yinya ")
            or not low.endswith(" yinya yaluy.")
            or has_token(low, "yinyay")
            or any(has_token(low, pron) for pron in ("yundu", "nyulu", "ngana", "jana", "nyajil", "nyajin"))
            or len(low.split()) != 3
        ):
            issues.append(f"{label}: rows 1-10 require TARGET yinya yaluy")
        if 11 <= seq <= 20 and (
            not low.startswith("yundu ")
            or not low.endswith(" yinyay nyajil.")
            or has_token(low, "yaluy")
            or has_token(low, "nyajin")
            or len(low.split()) != 4
        ):
            issues.append(f"{label}: rows 11-20 require Yundu TARGET yinyay nyajil")
        if 21 <= seq <= 30 and (
            not low.startswith("nyulu ")
            or not low.endswith(" yaluy nyajil.")
            or has_token(low, "yinyay")
            or has_token(low, "nyajin")
            or len(low.split()) != 4
        ):
            issues.append(f"{label}: rows 21-30 require Nyulu TARGET yaluy nyajil")
        if 31 <= seq <= 40 and (
            not low.startswith("ngana ")
            or not low.endswith(" yinyay nyajil.")
            or has_token(low, "yaluy")
            or has_token(low, "nyajin")
            or len(low.split()) != 4
        ):
            issues.append(f"{label}: rows 31-40 require Ngana TARGET yinyay nyajil")
        if 41 <= seq <= 50 and (
            not low.startswith("jana ")
            or not low.endswith(" yaluy nyajin.")
            or has_token(low, "yinyay")
            or has_token(low, "nyajil")
            or len(low.split()) != 4
        ):
            issues.append(f"{label}: rows 41-50 require Jana TARGET yaluy nyajin")
        if "saw" in english_low and not has_token(low, "nyajin"):
            issues.append(f"{label}: English saw requires nyajin")
        if re.search(r"\bsee(?:s)?\b", english_low) and not has_token(low, "nyajil"):
            issues.append(f"{label}: English see/sees requires nyajil")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied landform source-prose 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,))
    else:
        db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 233 draft", "operator-guide-2026-07-09", "draft under review", NOW),
        )
        batch_id = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()[0]

    collisions: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        found = db.execute(
            """
            SELECT b.label, s.seq, s.status
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(s.kuku)=lower(?) AND s.status IN ('accepted','revised','under_review')
            """,
            (kuku,),
        ).fetchall()
        if found:
            collisions.append(f"{seq:02d} {kuku}: {found}")
    if collisions:
        raise SystemExit("duplicate preflight failed:\n" + "\n".join(collisions))

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail="Checked dictionary entries for the ten Rule 232 landform/geography targets carried into Rule 233; checked Patz section 3.5 personal-pronoun paradigm for yundu, nyulu, ngana, and jana; Patz section 3.7 demonstratives for yinya, yaluy, and yinyay; and Patz/corpus perception evidence for nyajil nonpast and nyajin past.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail="Rule 233 is a construction consolidation over already sourced landform/geography nouns. It changes only the support frame: TARGET yinya yaluy, Yundu TARGET yinyay nyajil, Nyulu TARGET yaluy nyajil, Ngana TARGET yinyay nyajil, and Jana TARGET yaluy nyajin. It does not open landform case, route/travel/crossing, water-use, ecology, material-source, event, ownership, danger, or place-name semantics.",
        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 233 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="bank_275.py lower(kuku) collision scan for 50 planned surfaces",
        output_excerpt="collisions=0",
        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_275.py static guards passed: 50 explicit hand-authored rows, exactly one Rule 233 target noun per row, no loans, no target morphology, no denied Rule 185-186 or rejected landform token, no Rule 232 1sg band, no landform source-prose English, one postposed yinya/yaluy band, three nonpast perception bands, and one past perception band.",
        artifact_path="batch_scripts/bank_275.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, NOW, NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

    n = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'", (batch_id,)).fetchone()[0]
    print(f"banked {LABEL}: {n} under_review rows")
    return 0


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