#!/usr/bin/env python3
"""Bank batch-169: Rule 127 environmental lexical expansion after Rule 126."""

from __future__ import annotations

import datetime as dt
import json
import re
import sqlite3
import sys

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

DENY = {"yah", "ngawuya", "walnga", "maja-nga", "yunga", "bada-bada", "wangkar-wangkar", "biyul"}
CONSTRUCTION_CLITIC_MARKERS = ("-kuda", "-ngarr", "-ngurr", "-l-urr", "wawu-")
PRONOUN_A = {"ngayu", "ngana", "nganjin", "yundu", "yurra", "jana", "nyulu"}
SOURCED_COMITATIVES = ("ngawa-nji", "nganjan-anji", "jawun-unji", "juku-ji", "kambi-ji")
LAUGH_TARGET_SUFFIXES = ("-anka", "-anda", "-nda", "-ndu", "-nka")
LOAN_REQUIRED = ("mayngku", "wulman")


def js(values: list[str]) -> str:
    return json.dumps(values, ensure_ascii=False)


ROWS = [
    (1, "The firewood lay outside.",
     "Baya ngalkal-ba wunan.",
     "baya ngalkal-ba wuna-ny | firewood outside-LOC lie-PAST",
     "r127_rest_firewood_outside", 3, js(["baya", "ngalkal", "wunay"]), js([]),
     "Baya fire/firewood checked; used as firewood rest subject, not a new compound.", "0.84"),
    (2, "The stick lay on the ground.",
     "Juku bubu-ngu wunan.",
     "juku bubu-ngu wuna-ny | stick ground-LOC lie-PAST",
     "r127_rest_stick_ground", 3, js(["juku", "bubu", "wunay"]), js([]),
     "Juku covers tree/wood/stick; bubu-ngu retained LOC.", "0.84"),
    (3, "The paperbark lay in the shade.",
     "Buyku wabarr-ba wunan.",
     "buyku wabarr-ba wuna-ny | paperbark shade-LOC lie-PAST",
     "r127_rest_paperbark_shade", 3, js(["buyku", "wabarr", "wunay"]), js([]),
     "Buyku paperbark checked in dictionary and grammar.", "0.84"),
    (4, "The grass lay in the bag.",
     "Jikan balji-nga wunan.",
     "jikan balji-nga wuna-ny | grass bag-LOC lie-PAST",
     "r127_rest_grass_bag", 3, js(["jikan", "balji", "wunay"]), js([]),
     "Jikan grass plus retained balji-nga bag LOC.", "0.84"),
    (5, "The snake lay outside.",
     "Jarba ngalkal-ba wunan.",
     "jarba ngalkal-ba wuna-ny | snake outside-LOC lie-PAST",
     "r127_rest_snake_outside", 3, js(["jarba", "ngalkal", "wunay"]), js([]),
     "Jarba generic snake checked; outside LOC avoids duplicate grass row.", "0.84"),
    (6, "The frog lay in the water.",
     "Yirku-yirku bana-nga wunan.",
     "yirku-yirku bana-nga wuna-ny | frog water-LOC lie-PAST",
     "r127_rest_frog_water", 3, js(["yirku-yirku", "bana", "wunay"]), js([]),
     "Yirku-yirku frog and bana-nga water LOC are source-backed.", "0.84"),
    (7, "The firewood lay at camp.",
     "Baya bayan-ba wunan.",
     "baya bayan-ba wuna-ny | firewood camp-LOC lie-PAST",
     "r127_rest_firewood_camp", 3, js(["baya", "bayan", "wunay"]), js([]),
     "Baya as firewood with retained camp LOC.", "0.84"),
    (8, "The paperbark lay on the ground.",
     "Buyku bubu-ngu wunan.",
     "buyku bubu-ngu wuna-ny | paperbark ground-LOC lie-PAST",
     "r127_rest_paperbark_ground", 3, js(["buyku", "bubu", "wunay"]), js([]),
     "Buyku paperbark as ABS rest subject.", "0.84"),
    (9, "The stick lay on the road.",
     "Juku baral-ba wunan.",
     "juku baral-ba wuna-ny | stick road-LOC lie-PAST",
     "r127_rest_stick_road", 3, js(["juku", "baral", "wunay"]), js([]),
     "Juku stick with retained baral-ba road LOC.", "0.84"),
    (10, "The crocodile lay in the water.",
     "Bilngkumu bana-nga wunan.",
     "bilngkumu bana-nga wuna-ny | crocodile water-LOC lie-PAST",
     "r127_rest_crocodile_water", 3, js(["bilngkumu", "bana", "wunay"]), js([]),
     "Bilngkumu salt-water crocodile plus bana-nga water LOC.", "0.84"),

    (11, "The woman put the firewood on the ground.",
     "Jalbu-ngku baya bubu-ngu yijarrin.",
     "jalbu-ngku baya bubu-ngu yijarri-ny | woman-ERG firewood ground-LOC put-PAST",
     "r127_object_firewood_ground", 4, js(["jalbu", "baya", "bubu", "yijarril"]), js([]),
     "Common-noun A ERG; baya object in retained placement frame.", "0.84"),
    (12, "The man put the stick on the road.",
     "Dingkar-angka juku baral-ba yijarrin.",
     "dingkar-angka juku baral-ba yijarri-ny | man-ERG stick road-LOC put-PAST",
     "r127_object_stick_road", 4, js(["dingkar", "juku", "baral", "yijarril"]), js([]),
     "Juku stick object; no new instrument form.", "0.84"),
    (13, "Grandmother left the paperbark in the shade.",
     "Babi-ngka buyku wabarr-ba bawan.",
     "babi-ngka buyku wabarr-ba bawa-ny | grandmother-ERG paperbark shade-LOC leave-PAST",
     "r127_object_paperbark_shade", 4, js(["babi", "buyku", "wabarr", "bawal"]), js([]),
     "Buyku object in retained leave-location frame.", "0.84"),
    (14, "Mother put the grass in the bag.",
     "Ngamu-ngku jikan balji-nga yijarrin.",
     "ngamu-ngku jikan balji-nga yijarri-ny | mother-ERG grass bag-LOC put-PAST",
     "r127_object_grass_bag", 4, js(["ngamu", "jikan", "balji", "yijarril"]), js([]),
     "Jikan grass object; balji-nga retained.", "0.84"),
    (15, "The young man took water to camp.",
     "Warru-ngku bana bayan-ka wundin.",
     "warru-ngku bana bayan-ka wundi-ny | young.man-ERG water camp-DAT take-PAST",
     "r127_object_water_camp_goal", 4, js(["warru", "bana", "bayan", "wundil"]), js([]),
     "Bana object in source-backed wundi-l frame; common-noun A ERG.", "0.84"),
    (16, "Grandfather brought firewood from the house.",
     "Kami-ngka baya bayan-muny wundin.",
     "kami-ngka baya bayan-muny wundi-ny | grandfather-ERG firewood house-ABL bring-PAST",
     "r127_object_firewood_house_source", 4, js(["kami", "baya", "bayan", "wundil"]), js([]),
     "Baya firewood object plus retained bayan-muny source.", "0.84"),
    (17, "The old woman brought paperbark from the house.",
     "Wulbuman-angka buyku bayan-muny wundin.",
     "wulbuman-angka buyku bayan-muny wundi-ny | old.woman-ERG paperbark house-ABL bring-PAST",
     "r127_object_paperbark_house_source", 4, js(["wulbuman", "buyku", "bayan", "wundil"]), js([]),
     "Buyku object plus retained house ABL source.", "0.84"),
    (18, "I brought the stick from the house.",
     "Ngayu juku bayan-muny wundin.",
     "ngayu juku bayan-muny wundi-ny | I stick house-ABL bring-PAST",
     "r127_object_stick_house_source", 4, js(["ngayu", "juku", "bayan", "wundil"]), js([]),
     "Pronoun A bare; juku stick object plus ABL source.", "0.84"),
    (19, "We got water at camp.",
     "Ngana bana bayan-ba manin.",
     "ngana bana bayan-ba mani-ny | we water camp-LOC get-PAST",
     "r127_object_water_camp", 4, js(["ngana", "bana", "bayan", "manil"]), js([]),
     "Pronoun A bare; bana object in retained get-at-place frame.", "0.84"),
    (20, "The man saw the humpy.",
     "Dingkar-angka wurun nyajin.",
     "dingkar-angka wurun nyaji-ny | man-ERG humpy see-PAST",
     "r127_perception_man_humpy", 4, js(["dingkar", "wurun", "nyajil"]), js([]),
     "Wurun humpy/shelter object with ERG common-noun perceiver.", "0.84"),

    (21, "The child saw the cloud outside.",
     "Karrkay-ngku ngurrban ngalkal-ba nyajin.",
     "karrkay-ngku ngurrban ngalkal-ba nyaji-ny | child-ERG cloud outside-LOC see-PAST",
     "r127_perception_child_cloud_outside", 4, js(["karrkay", "ngurrban", "ngalkal", "nyajil"]), js([]),
     "Ngurrban cloud object; common-noun perceiver ERG.", "0.84"),
    (22, "I saw the cloud.",
     "Ngayu ngurrban nyajin.",
     "ngayu ngurrban nyaji-ny | I cloud see-PAST",
     "r127_perception_pronoun_cloud", 4, js(["ngayu", "ngurrban", "nyajil"]), js([]),
     "Pronoun A contrast for cloud perception.", "0.84"),
    (23, "The woman heard the wind.",
     "Jalbu-ngku muyar nyajin.",
     "jalbu-ngku muyar nyaji-ny | woman-ERG wind hear-PAST",
     "r127_perception_woman_wind", 4, js(["jalbu", "muyar", "nyajil"]), js([]),
     "Nyaji-l covers see/hear; muyar wind is heard here.", "0.84"),
    (24, "We heard the wind.",
     "Ngana muyar nyajin.",
     "ngana muyar nyaji-ny | we wind hear-PAST",
     "r127_perception_pronoun_wind", 4, js(["ngana", "muyar", "nyajil"]), js([]),
     "Pronoun A contrast for wind hearing.", "0.84"),
    (25, "The man saw the sky.",
     "Dingkar-angka jiri nyajin.",
     "dingkar-angka jiri nyaji-ny | man-ERG sky see-PAST",
     "r127_perception_man_sky", 4, js(["dingkar", "jiri", "nyajil"]), js([]),
     "Jiri sky object with common-noun perceiver ERG.", "0.84"),
    (26, "I saw the sun.",
     "Ngayu wungar nyajin.",
     "ngayu wungar nyaji-ny | I sun see-PAST",
     "r127_perception_pronoun_sun", 4, js(["ngayu", "wungar", "nyajil"]), js([]),
     "Wungar sun/day as perceived object; pronoun A bare.", "0.84"),
    (27, "Grandmother saw the bird in the tree.",
     "Babi-ngka buyi juku-ngu nyajin.",
     "babi-ngka buyi juku-ngu nyaji-ny | grandmother-ERG bird tree-LOC see-PAST",
     "r127_perception_grandmother_bird_tree", 4, js(["babi", "buyi", "juku", "nyajil"]), js([]),
     "Buyi bird plus juku-ngu tree LOC.", "0.84"),
    (28, "We saw the bird in the tree.",
     "Ngana buyi juku-ngu nyajin.",
     "ngana buyi juku-ngu nyaji-ny | we bird tree-LOC see-PAST",
     "r127_perception_pronoun_bird_tree", 4, js(["ngana", "buyi", "juku", "nyajil"]), js([]),
     "Pronoun A contrast for bird in tree.", "0.84"),
    (29, "The young man saw the snake outside.",
     "Warru-ngku jarba ngalkal-ba nyajin.",
     "warru-ngku jarba ngalkal-ba nyaji-ny | young.man-ERG snake outside-LOC see-PAST",
     "r127_perception_young_man_snake_outside", 4, js(["warru", "jarba", "ngalkal", "nyajil"]), js([]),
     "Jarba snake object; outside LOC avoids exact duplicate with grass rows.", "0.84"),
    (30, "I saw the crocodile in the water.",
     "Ngayu bilngkumu bana-nga nyajin.",
     "ngayu bilngkumu bana-nga nyaji-ny | I crocodile water-LOC see-PAST",
     "r127_perception_pronoun_crocodile_water", 4, js(["ngayu", "bilngkumu", "bana", "nyajil"]), js([]),
     "Bilngkumu crocodile plus sourced bana-nga water LOC.", "0.84"),

    (31, "The old man asked grandmother about water.",
     "Wulman babi-nda bana-ka babajin.",
     "wulman babi-nda bana-ka babaji-ny | old.man grandmother-LOC:pt water-DAT ask-PAST",
     "r127_ask_old_man_grandmother_water", 4, js(["wulman", "babi", "bana", "babaji"]), js(["wulman"]),
     "Bana-ka is source-backed; babaji-y asker remains ABS/S.", "0.86"),
    (32, "The young man asked mother about water.",
     "Warru ngamu-ndu bana-ka babajin.",
     "warru ngamu-ndu bana-ka babaji-ny | young.man mother-LOC:pt water-DAT ask-PAST",
     "r127_ask_young_man_mother_water", 4, js(["warru", "ngamu", "bana", "babaji"]), js([]),
     "Ask-about frame retained with sourced bana-ka topic.", "0.86"),
    (33, "The woman asked father about news.",
     "Jalbu nganjan-anda kuku-ku babajin.",
     "jalbu nganjan-anda kuku-ku babaji-ny | woman father-LOC:pt news-DAT ask-PAST",
     "r127_ask_woman_father_news", 4, js(["jalbu", "nganjan", "kuku", "babaji"]), js([]),
     "Kuku-ku DAT topic retained for ask-about maintenance.", "0.86"),
    (34, "The friend asked the girl about meat.",
     "Jawun maral-anda minya-ka babajin.",
     "jawun maral-anda minya-ka babaji-ny | friend girl-LOC:pt meat-DAT ask-PAST",
     "r127_ask_friend_girl_meat", 4, js(["jawun", "maral", "minya", "babaji"]), js([]),
     "Minya-ka retained; no ERG on asker.", "0.86"),
    (35, "The child asked grandfather about the mango.",
     "Karrkay kami-nda mayngku-ku babajin.",
     "karrkay kami-nda mayngku-ku babaji-ny | child grandfather-LOC:pt mango-DAT ask-PAST",
     "r127_ask_child_grandfather_mango", 4, js(["karrkay", "kami", "mayngku", "babaji"]), js(["mayngku"]),
     "Mayngku-ku retained and loan-logged.", "0.86"),

    (36, "The old man laughed at mother.",
     "Wulman ngamu-ndu yajarrin.",
     "wulman ngamu-ndu yajarri-ny | old.man mother-DAT:pt laugh-PAST",
     "r127_laugh_old_man_mother", 3, js(["wulman", "ngamu", "yajarril"]), js(["wulman"]),
     "DAT:pt target retained; no ERG on laugher.", "0.84"),
    (37, "Mother laughed at father.",
     "Ngamu nganjan-anda yajarrin.",
     "ngamu nganjan-anda yajarri-ny | mother father-DAT:pt laugh-PAST",
     "r127_laugh_mother_father", 3, js(["ngamu", "nganjan", "yajarril"]), js([]),
     "Duplicate repair changed only the sourced target.", "0.84"),
    (38, "Father laughed at grandmother.",
     "Nganjan babi-nda yajarrin.",
     "nganjan babi-nda yajarri-ny | father grandmother-DAT:pt laugh-PAST",
     "r127_laugh_father_grandmother", 3, js(["nganjan", "babi", "yajarril"]), js([]),
     "DAT:pt target retained.", "0.84"),
    (39, "The girl laughed at grandfather.",
     "Maral kami-nda yajarrin.",
     "maral kami-nda yajarri-ny | girl grandfather-DAT:pt laugh-PAST",
     "r127_laugh_girl_grandfather", 3, js(["maral", "kami", "yajarril"]), js([]),
     "DAT:pt target retained.", "0.84"),
    (40, "The friend laughed at mother.",
     "Jawun ngamu-ndu yajarrin.",
     "jawun ngamu-ndu yajarri-ny | friend mother-DAT:pt laugh-PAST",
     "r127_laugh_friend_mother", 3, js(["jawun", "ngamu", "yajarril"]), js([]),
     "DAT:pt target retained.", "0.84"),

    (41, "Grandmother went into the grass with the baby.",
     "Babi ngawa-nji jikan-ba dungan.",
     "babi ngawa-nji jikan-ba dunga-ny | grandmother baby-COMIT:pt grass-LOC go-PAST",
     "r127_comit_grandmother_baby_grass", 4, js(["babi", "ngawa", "jikan", "dungay"]), js([]),
     "Ngawa-nji closed comitative; jikan-ba grass LOC.", "0.84"),
    (42, "The young man went to the shade with a friend.",
     "Warru jawun-unji wabarr-ba dungan.",
     "warru jawun-unji wabarr-ba dunga-ny | young.man friend-COMIT:pt shade-LOC go-PAST",
     "r127_comit_young_man_friend_shade", 4, js(["warru", "jawun", "wabarr", "dungay"]), js([]),
     "Jawun-unji closed comitative plus shade LOC.", "0.84"),
    (43, "The woman went outside with father.",
     "Jalbu nganjan-anji ngalkal-ba dungan.",
     "jalbu nganjan-anji ngalkal-ba dunga-ny | woman father-COMIT:pt outside-LOC go-PAST",
     "r127_comit_woman_father_outside", 4, js(["jalbu", "nganjan", "ngalkal", "dungay"]), js([]),
     "Nganjan-anji closed comitative plus outside LOC.", "0.84"),
    (44, "The child went to camp with a stick.",
     "Karrkay juku-ji bayan-ba dungan.",
     "karrkay juku-ji bayan-ba dunga-ny | child stick-COMIT camp-LOC go-PAST",
     "r127_comit_child_stick_camp", 4, js(["karrkay", "juku", "bayan", "dungay"]), js([]),
     "Juku-ji is in the closed comitative set.", "0.84"),
    (45, "Mother went to camp with clothes.",
     "Ngamu kambi-ji bayan-ba dungan.",
     "ngamu kambi-ji bayan-ba dunga-ny | mother clothes-COMIT camp-LOC go-PAST",
     "r127_comit_mother_clothes_camp", 4, js(["ngamu", "kambi", "bayan", "dungay"]), js([]),
     "Kambi-ji closed comitative; retained camp LOC.", "0.84"),
    (46, "The old man is staying in the grass with the baby.",
     "Wulman jikan-ba bundanday ngawa-nji.",
     "wulman jikan-ba bunda-n-bunda-y ngawa-nji | old.man grass-LOC stay-REDUP-NONPAST baby-COMIT:pt",
     "r127_comit_old_man_baby_grass", 4, js(["wulman", "jikan", "bunday", "ngawa"]), js(["wulman"]),
     "Place-before-comitative order retained; wulman loan/contact form logged.", "0.84"),

    (47, "The man saw the snake outside.",
     "Dingkar-angka jarba ngalkal-ba nyajin.",
     "dingkar-angka jarba ngalkal-ba nyaji-ny | man-ERG snake outside-LOC see-PAST",
     "r127_perception_man_snake_outside", 4, js(["dingkar", "jarba", "ngalkal", "nyajil"]), js([]),
     "Jarba snake object with ERG common-noun perceiver.", "0.84"),
    (48, "The old woman saw the frog in the water.",
     "Wulbuman-angka yirku-yirku bana-nga nyajin.",
     "wulbuman-angka yirku-yirku bana-nga nyaji-ny | old.woman-ERG frog water-LOC see-PAST",
     "r127_perception_old_woman_frog_water", 4, js(["wulbuman", "yirku-yirku", "bana", "nyajil"]), js([]),
     "Yirku-yirku frog plus bana-nga water LOC.", "0.84"),
    (49, "I took the paperbark to camp.",
     "Ngayu buyku bayan-ka wundin.",
     "ngayu buyku bayan-ka wundi-ny | I paperbark camp-DAT take-PAST",
     "r127_object_paperbark_camp_goal", 4, js(["ngayu", "buyku", "bayan", "wundil"]), js([]),
     "Pronoun A bare; buyku object plus DAT goal.", "0.84"),
    (50, "We brought firewood from the house.",
     "Ngana baya bayan-muny wundin.",
     "ngana baya bayan-muny wundi-ny | we firewood house-ABL bring-PAST",
     "r127_object_firewood_house_source_pronoun", 4, js(["ngana", "baya", "bayan", "wundil"]), js([]),
     "Pronoun A bare; baya firewood object plus ABL source.", "0.84"),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", 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 in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        analysis_low = analysis.lower()
        try:
            json.loads(words_used)
            loan_values = json.loads(loans_used)
        except json.JSONDecodeError as exc:
            issues.append(f"{label}: JSON field failed: {exc}")
            loan_values = []
        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("r127_"):
            issues.append(f"{label}: Rule 127 batch frame must start with r127_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        for marker in CONSTRUCTION_CLITIC_MARKERS:
            if marker in low:
                issues.append(f"{label}: lexical batch must not reuse temporal clitic marker {marker}")
        for denied in DENY:
            if has_token(low, denied):
                issues.append(f"{label}: denied or out-of-scope token {denied!r}")
        for loan in LOAN_REQUIRED:
            if has_token(low, loan) and loan not in loan_values:
                issues.append(f"{label}: {loan} must be listed in loans_used")
        sense_pairs = [
            ("water", "bana"),
            ("firewood", "baya"),
            ("stick", "juku"),
            ("paperbark", "buyku"),
            ("grass", "jikan"),
            ("humpy", "wurun"),
            ("cloud", "ngurrban"),
            ("wind", "muyar"),
            ("sky", "jiri"),
            ("sun", "wungar"),
            ("bird", "buyi"),
            ("snake", "jarba"),
            ("crocodile", "bilngkumu"),
            ("frog", "yirku-yirku"),
        ]
        for english_head, kuku_head in sense_pairs:
            if english_head in english_low and kuku_head not in low:
                issues.append(f"{label}: English {english_head} row must use {kuku_head}")
        if has_token(low, "baya") and not any(word in analysis_low for word in ("fire", "firewood")):
            issues.append(f"{label}: baya must be glossed fire/firewood")
        if has_token(low, "juku") and not any(word in analysis_low for word in ("tree", "stick", "wood")):
            issues.append(f"{label}: juku must be glossed tree/stick/wood")
        if "babajin" in low and re.match(r"^[A-Za-z-]+-(?:ngka|angka|ngku)\b", kuku):
            issues.append(f"{label}: babaji-y asker drifted into ergative A marking")
        if "nyaji" in analysis_low:
            first = low.split()[0].strip(".,!?")
            if first not in PRONOUN_A and not re.search(r"-(?:ngka|angka|ngku)\b", first):
                issues.append(f"{label}: common-noun perceiver with nyaji-l should be ERG-marked")
        if "yajarrin" in low and not any(suffix in low for suffix in LAUGH_TARGET_SUFFIXES):
            issues.append(f"{label}: laugh target should show sourced DAT:pt target suffix")
        if "COMIT" in analysis and not any(form in low for form in SOURCED_COMITATIVES):
            issues.append(f"{label}: comitative form is not in the closed sourced set")
        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 127 draft: environmental lexical expansion after Rule 126", "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 127 source pass checked dictionary.yaml, Patz grammar, existing corpus lexemes, and planned-surface "
            "duplicates before authoring. Environmental heads were admitted only inside retained rest, object, perception, "
            "ask-about, laugh, transfer, and closed-comitative frames."
        ),
        command="rg over dictionary.yaml and grammar.md; sqlite lexeme readback and duplicate scan",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="dictionary-source-check",
        actor="claude-main",
        detail=(
            "Exact dictionary readback confirmed bana water, baya fire/firewood, juku tree/wood/stick, buyku paperbark, "
            "jikan grass, wurun humpy, ngurrban cloud, muyar wind, jiri sky, wungar sun, buyi bird, jarba snake, "
            "bilngkumu crocodile, and yirku-yirku frog."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="grammar-source-check",
        actor="claude-main",
        detail=(
            "Grammar controls checked classifier table heads, juku-ji/juku-ngu/juku-muny, bana-nga and bana-ka, "
            "jikan-ba, baya-nga and baya firewood object uses, wungar-a/wungar, ngurrban, muyar, buyku, jarba, "
            "bilngkumu, and yirku-yirku examples."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="risk-controls",
        actor="claude-main",
        detail=(
            "Controls: no new morphology; no biyul; no new instruments/comitatives/possessives from juku or animal heads; "
            "baya treated as fire/firewood with possible but unsubstantiated loan note, not loan-logged; mayngku and wulman "
            "loan/contact forms logged; common-noun nyaji-l perceivers ERG-marked; babaji-y askers not ERG-marked."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="existing-surface-scan",
        actor="claude-main",
        detail=(
            "Initial planned scan found one exact duplicate, Ngamu karrkay-anka yajarrin, already in batch-166. "
            "It was repaired to Ngamu nganjan-anda yajarrin. Final scan found no exact duplicates."
        ),
        command="sqlite exact-surface query over planned Batch 169 rows",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="process",
        event_type="process-capture-expanded",
        actor="claude-main",
        detail=(
            "Batch 169 stores source inventory, duplicate repair, static guards, row grouping, bank outcome, and later "
            "lint/review/close/export/docs evidence as process_events plus this process log."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    db.executemany(
        """
        INSERT INTO sentences(
            batch_id, seq, english, kuku, analysis, frame, tier, words_used,
            loans_used, evidence, status, confidence, rights_status, author,
            created_at, updated_at
        ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (
                batch_id, seq, english, kuku, analysis, frame, tier, words_used,
                loans_used, evidence, "under_review", confidence,
                "project_approved_synthetic_pending_elder_verification",
                "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 hand-authored Rule 127 environmental lexical-expansion rows under_review after static guards and duplicate checks.",
        command="python3 batch_scripts/bank_169.py",
        artifact_path="batch_scripts/bank_169.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="bank",
        event_type="row-inventory",
        actor="claude-main",
        detail=(
            "Rows 1-10 rest; 11-20 object location/source/goal and humpy perception; 21-30 perception/hearing; "
            "31-35 ask-about; 36-40 laugh targets; 41-46 closed comitatives; 47-50 additional animal/object rows."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    db.commit()

    count = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=?", (batch_id,)).fetchone()[0]
    avg_words = db.execute(
        "SELECT AVG(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1.0) FROM sentences WHERE batch_id=?",
        (batch_id,),
    ).fetchone()[0]
    process_events = db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (LABEL,)).fetchone()[0]
    print(f"banked {LABEL}: {count} rows under_review, avg_words={avg_words:.2f}, process_events={process_events}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
