#!/usr/bin/env python3
"""Bank batch-193: Rule 151 geography/water lexical expansion after Rule 150."""

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-193"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-193-geography-water-lexical-expansion-process.md"

TARGET_HEADS = {
    "wawubaja": "river",
    "baral": "road",
    "bana": "water",
    "jukar": "sand",
    "manjal": "mountain",
    "jalkaraburr": "mountain.peak",
    "daburri": "swamp",
    "dajali": "deep.water",
    "yalkan": "shallow.water",
    "ngalkal": "open.ground",
}
TARGET_ENGLISH = {
    "wawubaja": "river",
    "baral": "road",
    "bana": "water",
    "jukar": "sand",
    "manjal": "mountain",
    "jalkaraburr": "mountain peak",
    "daburri": "swamp",
    "dajali": "deep water",
    "yalkan": "shallow water",
    "ngalkal": "open ground",
}
PRONOUN_A = {"ngayu", "ngana", "jana"}
COMMON_A = {"ngamu-ngku", "nganjan-angka", "babi-ngka", "karrkay-ngku", "kami-ngka", "jalbu-ngku", "dingkar-angka"}
SUPPORT_HEADS = {"yinyay": "there", "nyaji-l": "see; hear; perceive"}
FORBIDDEN_HEADS = {"wuburr", "balay", "dubar"}
DENY_KUKU = {
    "dama", "daman", "damanka", "nyurrba", "nyurrban", "yaka", "yakan", "kuni", "kunin", "baka", "bakan",
    "wundi", "wundin", "bangka", "bangkan", "balka", "balkan", "kaja", "kajan", "yurril", "yurrin",
    "kida", "kidan", "jurrnga", "jurrngan", "yilba", "yilban", "duda", "dudan", "nyanda", "nyandan",
    "mani", "manin", "yijarri", "yijarrin", "daka", "dakan", "waju", "wajun", "wunba", "mayi",
    "dunga", "dungan", "dungay", "kadan", "kaday", "kada", "janji", "janjil", "mariji", "marijin",
}
DENY_ENGLISH = (
    "go", "went", "come", "came", "walk", "walked", "run", "ran", "swim", "swam", "bathe", "bathed",
    "drink", "drank", "take", "took", "get", "got", "cut", "cutting", "spear", "speared", "kill",
    "killed", "catch", "caught", "hunt", "hunting", "fish with", "dive", "dived", "road along",
    "mountain top", "mission", "place name",
)


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 river is there.", "Wawubaja yinyay.",
        "wawubaja yinyay | river there", "r151_deictic_river", ["wawubaja", "yinyay"], "Patz grammar lists wawubaja 'a river' and yinyay 'there'; dictionary confirms river."),
    row(2, "The road is there.", "Baral yinyay.",
        "baral yinyay | road there", "r151_deictic_road", ["baral", "yinyay"], "Dictionary confirms baral road/path noun; grammar has baral road/path examples and yinyay there."),
    row(3, "The water is there.", "Bana yinyay.",
        "bana yinyay | water there", "r151_deictic_water", ["bana", "yinyay"], "Dictionary and Patz grammar confirm bana water and yinyay there."),
    row(4, "The sand is there.", "Jukar yinyay.",
        "jukar yinyay | sand there", "r151_deictic_sand", ["jukar", "yinyay"], "Dictionary confirms jukar sand; grammar confirms yinyay local demonstrative."),
    row(5, "The mountain is there.", "Manjal yinyay.",
        "manjal yinyay | mountain there", "r151_deictic_mountain", ["manjal", "yinyay"], "Dictionary confirms manjal mountain; Patz grammar confirms manjal-ba mountain-LOC."),
    row(6, "The mountain peak is there.", "Jalkaraburr yinyay.",
        "jalkaraburr yinyay | mountain.peak there", "r151_deictic_peak", ["jalkaraburr", "yinyay"], "Dictionary confirms jalkaraburr high mountain reaches / mountain peak."),
    row(7, "The swamp is there.", "Daburri yinyay.",
        "daburri yinyay | swamp there", "r151_deictic_swamp", ["daburri", "yinyay"], "Dictionary confirms daburri brackish swamp water."),
    row(8, "The deep water is there.", "Dajali yinyay.",
        "dajali yinyay | deep.water there", "r151_deictic_deep_water", ["dajali", "yinyay"], "Dictionary confirms dajali deep water; Patz text has dajali in deep-water warning."),
    row(9, "The shallow water is there.", "Yalkan yinyay.",
        "yalkan yinyay | shallow.water there", "r151_deictic_shallow_water", ["yalkan", "yinyay"], "Dictionary confirms yalkan shallow water; Patz text has yalkan-ba shallow-water LOC."),
    row(10, "The open ground is there.", "Ngalkal yinyay.",
        "ngalkal yinyay | open.ground there", "r151_deictic_open_ground", ["ngalkal", "yinyay"], "Dictionary confirms ngalkal outside/open ground; grammar confirms yinyay there."),
    row(11, "I saw the river.", "Ngayu wawubaja nyajin.",
        "ngayu wawubaja nyaji-ny | I river see-PAST", "r151_past_i_river", ["ngayu", "wawubaja", "nyaji-l"], "Pronoun A bare; target geography noun bare."),
    row(12, "We saw the road.", "Ngana baral nyajin.",
        "ngana baral nyaji-ny | we road see-PAST", "r151_past_we_road", ["ngana", "baral", "nyaji-l"], "Pronoun A bare; baral selected as road noun, not feel verb."),
    row(13, "They saw the water.", "Jana bana nyajin.",
        "jana bana nyaji-ny | they water see-PAST", "r151_past_they_water", ["jana", "bana", "nyaji-l"], "Pronoun A bare; water object."),
    row(14, "Mother saw the sand.", "Ngamu-ngku jukar nyajin.",
        "ngamu-ngku jukar nyaji-ny | mother-ERG sand see-PAST", "r151_past_mother_sand", ["ngamu", "jukar", "nyaji-l"], "Common-noun A ERG; sand object."),
    row(15, "Father saw the mountain.", "Nganjan-angka manjal nyajin.",
        "nganjan-angka manjal nyaji-ny | father-ERG mountain see-PAST", "r151_past_father_mountain", ["nganjan", "manjal", "nyaji-l"], "Common-noun A ERG; mountain object."),
    row(16, "The child saw the mountain peak.", "Karrkay-ngku jalkaraburr nyajin.",
        "karrkay-ngku jalkaraburr nyaji-ny | child-ERG mountain.peak see-PAST", "r151_past_child_peak", ["karrkay", "jalkaraburr", "nyaji-l"], "Common-noun A ERG; jalkaraburr peak object."),
    row(17, "Grandmother saw the swamp.", "Babi-ngka daburri nyajin.",
        "babi-ngka daburri nyaji-ny | grandmother-ERG swamp see-PAST", "r151_past_grandmother_swamp", ["babi", "daburri", "nyaji-l"], "Common-noun A ERG; swamp object."),
    row(18, "Grandfather saw the deep water.", "Kami-ngka dajali nyajin.",
        "kami-ngka dajali nyaji-ny | grandfather-ERG deep.water see-PAST", "r151_past_grandfather_deep_water", ["kami", "dajali", "nyaji-l"], "Common-noun A ERG; dajali selected as deep-water noun."),
    row(19, "The woman saw the shallow water.", "Jalbu-ngku yalkan nyajin.",
        "jalbu-ngku yalkan nyaji-ny | woman-ERG shallow.water see-PAST", "r151_past_woman_shallow_water", ["jalbu", "yalkan", "nyaji-l"], "Common-noun A ERG; yalkan selected as shallow-water noun."),
    row(20, "The man saw the open ground.", "Dingkar-angka ngalkal nyajin.",
        "dingkar-angka ngalkal nyaji-ny | man-ERG open.ground see-PAST", "r151_past_man_open_ground", ["dingkar", "ngalkal", "nyaji-l"], "Common-noun A ERG; ngalkal selected as outside/open-ground noun."),
    row(21, "I see the road.", "Ngayu baral nyajil.",
        "ngayu baral nyaji-l | I road see-NONPAST", "r151_present_i_road", ["ngayu", "baral", "nyaji-l"], "Pronoun A bare; baral road noun."),
    row(22, "We see the water.", "Ngana bana nyajil.",
        "ngana bana nyaji-l | we water see-NONPAST", "r151_present_we_water", ["ngana", "bana", "nyaji-l"], "Pronoun A bare; water object."),
    row(23, "They see the sand.", "Jana jukar nyajil.",
        "jana jukar nyaji-l | they sand see-NONPAST", "r151_present_they_sand", ["jana", "jukar", "nyaji-l"], "Pronoun A bare; sand object."),
    row(24, "Mother sees the mountain.", "Ngamu-ngku manjal nyajil.",
        "ngamu-ngku manjal nyaji-l | mother-ERG mountain see-NONPAST", "r151_present_mother_mountain", ["ngamu", "manjal", "nyaji-l"], "Common-noun A ERG; mountain object."),
    row(25, "Father sees the mountain peak.", "Nganjan-angka jalkaraburr nyajil.",
        "nganjan-angka jalkaraburr nyaji-l | father-ERG mountain.peak see-NONPAST", "r151_present_father_peak", ["nganjan", "jalkaraburr", "nyaji-l"], "Common-noun A ERG; jalkaraburr peak object."),
    row(26, "The child sees the swamp.", "Karrkay-ngku daburri nyajil.",
        "karrkay-ngku daburri nyaji-l | child-ERG swamp see-NONPAST", "r151_present_child_swamp", ["karrkay", "daburri", "nyaji-l"], "Common-noun A ERG; swamp object."),
    row(27, "Grandmother sees the deep water.", "Babi-ngka dajali nyajil.",
        "babi-ngka dajali nyaji-l | grandmother-ERG deep.water see-NONPAST", "r151_present_grandmother_deep_water", ["babi", "dajali", "nyaji-l"], "Common-noun A ERG; dajali deep-water noun."),
    row(28, "Grandfather sees the shallow water.", "Kami-ngka yalkan nyajil.",
        "kami-ngka yalkan nyaji-l | grandfather-ERG shallow.water see-NONPAST", "r151_present_grandfather_shallow_water", ["kami", "yalkan", "nyaji-l"], "Common-noun A ERG; yalkan shallow-water noun."),
    row(29, "The woman sees the open ground.", "Jalbu-ngku ngalkal nyajil.",
        "jalbu-ngku ngalkal nyaji-l | woman-ERG open.ground see-NONPAST", "r151_present_woman_open_ground", ["jalbu", "ngalkal", "nyaji-l"], "Common-noun A ERG; ngalkal open-ground noun."),
    row(30, "The man sees the river.", "Dingkar-angka wawubaja nyajil.",
        "dingkar-angka wawubaja nyaji-l | man-ERG river see-NONPAST", "r151_present_man_river", ["dingkar", "wawubaja", "nyaji-l"], "Common-noun A ERG; river object."),
    row(31, "I saw the river there.", "Ngayu wawubaja yinyay nyajin.",
        "ngayu wawubaja yinyay nyaji-ny | I river there see-PAST", "r151_past_i_river_there", ["ngayu", "wawubaja", "yinyay", "nyaji-l"], "Pronoun A bare; deictic support yinyay."),
    row(32, "We saw the road there.", "Ngana baral yinyay nyajin.",
        "ngana baral yinyay nyaji-ny | we road there see-PAST", "r151_past_we_road_there", ["ngana", "baral", "yinyay", "nyaji-l"], "Pronoun A bare; baral road noun plus yinyay."),
    row(33, "They saw the water there.", "Jana bana yinyay nyajin.",
        "jana bana yinyay nyaji-ny | they water there see-PAST", "r151_past_they_water_there", ["jana", "bana", "yinyay", "nyaji-l"], "Pronoun A bare; water object plus yinyay."),
    row(34, "Mother saw the sand there.", "Ngamu-ngku jukar yinyay nyajin.",
        "ngamu-ngku jukar yinyay nyaji-ny | mother-ERG sand there see-PAST", "r151_past_mother_sand_there", ["ngamu", "jukar", "yinyay", "nyaji-l"], "Common-noun A ERG; sand object plus yinyay."),
    row(35, "Father saw the mountain there.", "Nganjan-angka manjal yinyay nyajin.",
        "nganjan-angka manjal yinyay nyaji-ny | father-ERG mountain there see-PAST", "r151_past_father_mountain_there", ["nganjan", "manjal", "yinyay", "nyaji-l"], "Common-noun A ERG; mountain object plus yinyay."),
    row(36, "The child saw the mountain peak there.", "Karrkay-ngku jalkaraburr yinyay nyajin.",
        "karrkay-ngku jalkaraburr yinyay nyaji-ny | child-ERG mountain.peak there see-PAST", "r151_past_child_peak_there", ["karrkay", "jalkaraburr", "yinyay", "nyaji-l"], "Common-noun A ERG; jalkaraburr peak plus yinyay."),
    row(37, "Grandmother saw the swamp there.", "Babi-ngka daburri yinyay nyajin.",
        "babi-ngka daburri yinyay nyaji-ny | grandmother-ERG swamp there see-PAST", "r151_past_grandmother_swamp_there", ["babi", "daburri", "yinyay", "nyaji-l"], "Common-noun A ERG; swamp object plus yinyay."),
    row(38, "Grandfather saw the deep water there.", "Kami-ngka dajali yinyay nyajin.",
        "kami-ngka dajali yinyay nyaji-ny | grandfather-ERG deep.water there see-PAST", "r151_past_grandfather_deep_water_there", ["kami", "dajali", "yinyay", "nyaji-l"], "Common-noun A ERG; dajali plus yinyay."),
    row(39, "The woman saw the shallow water there.", "Jalbu-ngku yalkan yinyay nyajin.",
        "jalbu-ngku yalkan yinyay nyaji-ny | woman-ERG shallow.water there see-PAST", "r151_past_woman_shallow_water_there", ["jalbu", "yalkan", "yinyay", "nyaji-l"], "Common-noun A ERG; yalkan plus yinyay."),
    row(40, "The man saw the open ground there.", "Dingkar-angka ngalkal yinyay nyajin.",
        "dingkar-angka ngalkal yinyay nyaji-ny | man-ERG open.ground there see-PAST", "r151_past_man_open_ground_there", ["dingkar", "ngalkal", "yinyay", "nyaji-l"], "Common-noun A ERG; ngalkal plus yinyay."),
    row(41, "Father sees the river.", "Nganjan-angka wawubaja nyajil.",
        "nganjan-angka wawubaja nyaji-l | father-ERG river see-NONPAST", "r151_present_father_river", ["nganjan", "wawubaja", "nyaji-l"], "Common-noun A ERG; river object."),
    row(42, "The child sees the road.", "Karrkay-ngku baral nyajil.",
        "karrkay-ngku baral nyaji-l | child-ERG road see-NONPAST", "r151_present_child_road", ["karrkay", "baral", "nyaji-l"], "Common-noun A ERG; baral road noun."),
    row(43, "Grandmother sees the water.", "Babi-ngka bana nyajil.",
        "babi-ngka bana nyaji-l | grandmother-ERG water see-NONPAST", "r151_present_grandmother_water", ["babi", "bana", "nyaji-l"], "Common-noun A ERG; water object."),
    row(44, "Grandfather sees the sand.", "Kami-ngka jukar nyajil.",
        "kami-ngka jukar nyaji-l | grandfather-ERG sand see-NONPAST", "r151_present_grandfather_sand", ["kami", "jukar", "nyaji-l"], "Common-noun A ERG; sand object."),
    row(45, "The woman sees the mountain.", "Jalbu-ngku manjal nyajil.",
        "jalbu-ngku manjal nyaji-l | woman-ERG mountain see-NONPAST", "r151_present_woman_mountain", ["jalbu", "manjal", "nyaji-l"], "Common-noun A ERG; mountain object."),
    row(46, "The man sees the mountain peak.", "Dingkar-angka jalkaraburr nyajil.",
        "dingkar-angka jalkaraburr nyaji-l | man-ERG mountain.peak see-NONPAST", "r151_present_man_peak", ["dingkar", "jalkaraburr", "nyaji-l"], "Common-noun A ERG; jalkaraburr peak object."),
    row(47, "I see the swamp.", "Ngayu daburri nyajil.",
        "ngayu daburri nyaji-l | I swamp see-NONPAST", "r151_present_i_swamp", ["ngayu", "daburri", "nyaji-l"], "Pronoun A bare; swamp object."),
    row(48, "We see the deep water.", "Ngana dajali nyajil.",
        "ngana dajali nyaji-l | we deep.water see-NONPAST", "r151_present_we_deep_water", ["ngana", "dajali", "nyaji-l"], "Pronoun A bare; dajali deep-water noun."),
    row(49, "They see the shallow water.", "Jana yalkan nyajil.",
        "jana yalkan nyaji-l | they shallow.water see-NONPAST", "r151_present_they_shallow_water", ["jana", "yalkan", "nyaji-l"], "Pronoun A bare; yalkan shallow-water noun."),
    row(50, "Mother sees the open ground.", "Ngamu-ngku ngalkal nyajil.",
        "ngamu-ngku ngalkal nyaji-l | mother-ERG open.ground see-NONPAST", "r151_present_mother_open_ground", ["ngamu", "ngalkal", "nyaji-l"], "Common-noun A ERG; ngalkal open-ground noun."),
]


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|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu)\b", low) is not None


def english_has_denied(english_low: str, denied: str) -> bool:
    if " " in denied:
        return denied in english_low
    return 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("r151_"):
            issues.append(f"{label}: Rule 151 frame must start with r151_")
        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 new loans are admitted in Rule 151")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied action/travel token {denied!r}")
        for denied in FORBIDDEN_HEADS:
            if has_token(low, denied):
                issues.append(f"{label}: forbidden place-name/adjective trap {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 151 target head, found {targets}")
        for head in targets:
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if TARGET_HEADS[head] not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {TARGET_HEADS[head]}")
            if TARGET_ENGLISH[head] not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {TARGET_ENGLISH[head]!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if has_token(low, "baral") and "feel" in english_low:
            issues.append(f"{label}: baral must not be used as perception verb 'feel'")
        if has_token(low, "dajali") and "deep water" not in english_low:
            issues.append(f"{label}: dajali must be translated as lexicalized deep water")
        if has_token(low, "yalkan") and "shallow water" not in english_low:
            issues.append(f"{label}: yalkan must be translated as lexicalized shallow water")
        for support, gloss in SUPPORT_HEADS.items():
            if (support == "yinyay" and has_token(low, support)) or (support == "nyaji-l" and ("nyajin" in low or "nyajil" in low)):
                if support not in words:
                    issues.append(f"{label}: support head {support} ({gloss}) missing from words_used")
        if "nyajin" in low or "nyajil" in low:
            first = first_word(low)
            if first not in PRONOUN_A and first not in COMMON_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun or ERG-marked common noun")
        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 travel/action/place-name 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 151 draft: geography/water lexical expansion after Rule 150", "operator-guide-2026-07-07", "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 151 source pass admitted geography/water targets wawubaja river, baral road/path, bana water, "
            "jukar sand, manjal mountain, jalkaraburr mountain peak, daburri brackish swamp water, dajali deep "
            "water, yalkan shallow water, and ngalkal outside/open ground. Dictionary, Patz grammar, lexeme-table, "
            "and corpus-surface readback completed; wuburr was excluded because the working dictionary entry is "
            "place-name/mission-marked despite grammar mountain-top examples."
        ),
        command="dictionary.yaml exact readback; grammar.md exact occurrence readback; sqlite lexeme and surface 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 151 is a lexical identification pass for bare geography/water heads. It uses deictic nominal "
            "clauses, bare past perception, present perception, and past perception with yinyay. It excludes target "
            "case forms, target compounds, travel/swimming/bathing/diving/drinking/water-taking/road-traversal "
            "semantics, place-name-only entries, and all carry-forward implement/action traps from Rules 149-150."
        ),
        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_193.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail=(
            "Static guards passed: one bare geography/water target per row, selected English senses enforced, "
            "dajali/yalkan lexicalized as deep/shallow water, baral forced to road/path noun, no wuburr/balay/dubar "
            "trap, no travel/action/water-use field, no target case or compound morphology, common-noun A ERG, and "
            "pronoun A bare."
        ),
        command="python3 batch_scripts/bank_193.py static scan",
        artifact_path="batch_scripts/bank_193.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, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence,
             "under_review", confidence, "claude-main", NOW, NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="bank",
        event_type="bank-success",
        actor="claude-main",
        detail="Banked 50 under_review Rule 151 geography/water lexical-expansion rows.",
        command="python3 batch_scripts/bank_193.py",
        artifact_path="batch_scripts/bank_193.py",
        created_at=NOW,
    )
    db.commit()

    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    under_review = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    print(f"banked {LABEL}: rows=50, under_review={under_review}, verified_before_close={verified}")
    return 0


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