#!/usr/bin/env python3
"""Bank batch-172: Rule 130 construction consolidation after Rule 129."""

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

DENY = {"yah", "ngawuya", "walnga", "maja-nga", "yunga", "bada-bada", "wangkar-wangkar", "biyul", "warrur"}
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, "Leaves lay on the ground.",
     "Birra bubu-ngu wunan.",
     "birra bubu-ngu wuna-ny | leaf ground-LOC lie-PAST",
     "r130_rest_leaf_ground", 3, js(["birra", "bubu", "wunay"]), js([]),
     "Rule 129 birra leaf sense in retained bubu-ngu/wuna-y frame.", "0.84"),
    (2, "Bark lay in the shade.",
     "Dumbul wabarr-ba wunan.",
     "dumbul wabarr-ba wuna-ny | bark shade-LOC lie-PAST",
     "r130_rest_bark_shade", 3, js(["dumbul", "wabarr", "wunay"]), js([]),
     "Rule 129 dumbul bark sense in retained wabarr-ba/wuna-y frame.", "0.84"),
    (3, "Smoke came from the scrub.",
     "Kubu madja-muny kadan.",
     "kubu madja-muny kada-ny | smoke scrub-ABL come-PAST",
     "r130_smoke_scrub_source", 3, js(["kubu", "madja", "kaday"]), js([]),
     "Kubu smoke in retained source-motion frame; madja-muny is source.", "0.84"),
    (4, "The stone lay in the bag.",
     "Kulji balji-nga wunan.",
     "kulji balji-nga wuna-ny | stone bag-LOC lie-PAST",
     "r130_rest_stone_bag", 3, js(["kulji", "balji", "wunay"]), js([]),
     "Kulji stone/rock, not mountain, in retained balji-nga rest frame.", "0.84"),
    (5, "Sand lay on the ground.",
     "Jukar bubu-ngu wunan.",
     "jukar bubu-ngu wuna-ny | sand ground-LOC lie-PAST",
     "r130_rest_sand_ground", 3, js(["jukar", "bubu", "wunay"]), js([]),
     "Jukar sand in retained ground rest frame.", "0.84"),
    (6, "Seeds lay in the bag.",
     "Diburr balji-nga wunan.",
     "diburr balji-nga wuna-ny | seed bag-LOC lie-PAST",
     "r130_rest_seed_bag", 3, js(["diburr", "balji", "wunay"]), js([]),
     "Diburr seed sense selected; retained bag rest frame.", "0.84"),
    (7, "The flower lay outside.",
     "Nganka ngalkal-ba wunan.",
     "nganka ngalkal-ba wuna-ny | flower outside-LOC lie-PAST",
     "r130_rest_flower_outside", 3, js(["nganka", "ngalkal", "wunay"]), js([]),
     "Nganka flower in retained outside rest frame.", "0.84"),
    (8, "Fog lay at camp.",
     "Ngurrbal bayan-ba wunan.",
     "ngurrbal bayan-ba wuna-ny | fog camp-LOC lie-PAST",
     "r130_rest_fog_camp", 3, js(["ngurrbal", "bayan", "wunay"]), js([]),
     "Ngurrbal fog in retained camp LOC rest frame.", "0.84"),
    (9, "The camp is on the mountain.",
     "Bayan manjal-ba janay.",
     "bayan manjal-ba jana-y | camp mountain-LOC stand/be-NONPAST",
     "r130_stand_camp_mountain", 3, js(["bayan", "manjal", "janay"]), js([]),
     "Manjal-ba mountain LOC with retained jana-y stand/be frame.", "0.84"),
    (10, "The tree stands in the scrub.",
     "Juku madja-nga janay.",
     "juku madja-nga jana-y | tree scrub-LOC stand/be-NONPAST",
     "r130_stand_tree_scrub", 3, js(["juku", "madja", "janay"]), js([]),
     "Madja-nga scrub LOC with retained jana-y stand/be frame.", "0.84"),

    (11, "The man put leaves on the ground.",
     "Dingkar-angka birra bubu-ngu yijarrin.",
     "dingkar-angka birra bubu-ngu yijarri-ny | man-ERG leaf ground-LOC put-PAST",
     "r130_place_leaf_ground", 4, js(["dingkar", "birra", "bubu", "yijarril"]), js([]),
     "Birra leaf object in retained placement frame; common-noun A ERG.", "0.84"),
    (12, "The woman left bark in the shade.",
     "Jalbu-ngku dumbul wabarr-ba bawan.",
     "jalbu-ngku dumbul wabarr-ba bawa-ny | woman-ERG bark shade-LOC leave-PAST",
     "r130_leave_bark_shade", 4, js(["jalbu", "dumbul", "wabarr", "bawal"]), js([]),
     "Dumbul bark object in retained leave-location frame.", "0.84"),
    (13, "The child put the stone in the bag.",
     "Karrkay-ngku kulji balji-nga yijarrin.",
     "karrkay-ngku kulji balji-nga yijarri-ny | child-ERG stone bag-LOC put-PAST",
     "r130_place_stone_bag", 4, js(["karrkay", "kulji", "balji", "yijarril"]), js([]),
     "Kulji stone object in retained placement frame; no instrument analogy.", "0.84"),
    (14, "Grandmother left sand on the ground.",
     "Babi-ngka jukar bubu-ngu bawan.",
     "babi-ngka jukar bubu-ngu bawa-ny | grandmother-ERG sand ground-LOC leave-PAST",
     "r130_leave_sand_ground", 4, js(["babi", "jukar", "bubu", "bawal"]), js([]),
     "Jukar sand object in retained leave-location frame.", "0.84"),
    (15, "Mother put seeds in the bag.",
     "Ngamu-ngku diburr balji-nga yijarrin.",
     "ngamu-ngku diburr balji-nga yijarri-ny | mother-ERG seed bag-LOC put-PAST",
     "r130_place_seed_bag", 4, js(["ngamu", "diburr", "balji", "yijarril"]), js([]),
     "Diburr seed sense in retained placement frame.", "0.84"),
    (16, "Grandfather left the flower outside.",
     "Kami-ngka nganka ngalkal-ba bawan.",
     "kami-ngka nganka ngalkal-ba bawa-ny | grandfather-ERG flower outside-LOC leave-PAST",
     "r130_leave_flower_outside", 4, js(["kami", "nganka", "ngalkal", "bawal"]), js([]),
     "Nganka flower object plus retained ngalkal-ba outside LOC.", "0.84"),
    (17, "The old woman brought the stone from the house.",
     "Wulbuman-angka kulji bayan-muny wundin.",
     "wulbuman-angka kulji bayan-muny wundi-ny | old.woman-ERG stone house-ABL bring-PAST",
     "r130_transfer_stone_house_source", 4, js(["wulbuman", "kulji", "bayan", "wundil"]), js([]),
     "Kulji stone object plus retained bayan-muny source.", "0.84"),
    (18, "The young man brought sand from camp.",
     "Warru-ngku jukar bayan-muny wundin.",
     "warru-ngku jukar bayan-muny wundi-ny | young.man-ERG sand camp-ABL bring-PAST",
     "r130_transfer_sand_camp_source", 4, js(["warru", "jukar", "bayan", "wundil"]), js([]),
     "Jukar sand object plus retained bayan-muny source.", "0.84"),
    (19, "I brought bark from the scrub.",
     "Ngayu dumbul madja-muny wundin.",
     "ngayu dumbul madja-muny wundi-ny | I bark scrub-ABL bring-PAST",
     "r130_transfer_pronoun_bark_scrub_source", 4, js(["ngayu", "dumbul", "madja", "wundil"]), js([]),
     "Pronoun A bare; dumbul bark object plus madja-muny source.", "0.84"),
    (20, "We took seeds to camp.",
     "Ngana diburr bayan-ka wundin.",
     "ngana diburr bayan-ka wundi-ny | we seed camp-DAT take-PAST",
     "r130_transfer_pronoun_seed_camp_goal", 4, js(["ngana", "diburr", "bayan", "wundil"]), js([]),
     "Pronoun A bare; diburr seed object plus bayan-ka goal.", "0.84"),

    (21, "Grandmother saw leaves on the ground.",
     "Babi-ngka birra bubu-ngu nyajin.",
     "babi-ngka birra bubu-ngu nyaji-ny | grandmother-ERG leaf ground-LOC see-PAST",
     "r130_perception_grandmother_leaf_ground", 4, js(["babi", "birra", "bubu", "nyajil"]), js([]),
     "Birra leaf perceived object; common-noun perceiver ERG.", "0.84"),
    (22, "I saw leaves on the ground.",
     "Ngayu birra bubu-ngu nyajin.",
     "ngayu birra bubu-ngu nyaji-ny | I leaf ground-LOC see-PAST",
     "r130_perception_pronoun_leaf_ground", 4, js(["ngayu", "birra", "bubu", "nyajil"]), js([]),
     "Pronoun A bare contrast for leaf perception.", "0.84"),
    (23, "The man saw bark in the shade.",
     "Dingkar-angka dumbul wabarr-ba nyajin.",
     "dingkar-angka dumbul wabarr-ba nyaji-ny | man-ERG bark shade-LOC see-PAST",
     "r130_perception_man_bark_shade", 4, js(["dingkar", "dumbul", "wabarr", "nyajil"]), js([]),
     "Dumbul bark perceived object; common-noun perceiver ERG.", "0.84"),
    (24, "We saw bark in the shade.",
     "Ngana dumbul wabarr-ba nyajin.",
     "ngana dumbul wabarr-ba nyaji-ny | we bark shade-LOC see-PAST",
     "r130_perception_pronoun_bark_shade", 4, js(["ngana", "dumbul", "wabarr", "nyajil"]), js([]),
     "Pronoun A bare contrast for bark perception.", "0.84"),
    (25, "The child saw smoke from the scrub.",
     "Karrkay-ngku kubu madja-muny nyajin.",
     "karrkay-ngku kubu madja-muny nyaji-ny | child-ERG smoke scrub-ABL see-PAST",
     "r130_perception_child_smoke_scrub_source", 4, js(["karrkay", "kubu", "madja", "nyajil"]), js([]),
     "Kubu smoke perceived object plus madja-muny source; common-noun perceiver ERG.", "0.84"),
    (26, "I saw smoke from the scrub.",
     "Ngayu kubu madja-muny nyajin.",
     "ngayu kubu madja-muny nyaji-ny | I smoke scrub-ABL see-PAST",
     "r130_perception_pronoun_smoke_scrub_source", 4, js(["ngayu", "kubu", "madja", "nyajil"]), js([]),
     "Pronoun A bare contrast for smoke-source perception.", "0.84"),
    (27, "The woman saw sand on the ground.",
     "Jalbu-ngku jukar bubu-ngu nyajin.",
     "jalbu-ngku jukar bubu-ngu nyaji-ny | woman-ERG sand ground-LOC see-PAST",
     "r130_perception_woman_sand_ground", 4, js(["jalbu", "jukar", "bubu", "nyajil"]), js([]),
     "Jukar sand perceived object; common-noun perceiver ERG.", "0.84"),
    (28, "We saw sand on the ground.",
     "Ngana jukar bubu-ngu nyajin.",
     "ngana jukar bubu-ngu nyaji-ny | we sand ground-LOC see-PAST",
     "r130_perception_pronoun_sand_ground", 4, js(["ngana", "jukar", "bubu", "nyajil"]), js([]),
     "Pronoun A bare contrast for sand perception.", "0.84"),
    (29, "The young man saw fog at camp.",
     "Warru-ngku ngurrbal bayan-ba nyajin.",
     "warru-ngku ngurrbal bayan-ba nyaji-ny | young.man-ERG fog camp-LOC see-PAST",
     "r130_perception_young_man_fog_camp", 4, js(["warru", "ngurrbal", "bayan", "nyajil"]), js([]),
     "Ngurrbal fog perceived object; common-noun perceiver ERG.", "0.84"),
    (30, "I saw fog at camp.",
     "Ngayu ngurrbal bayan-ba nyajin.",
     "ngayu ngurrbal bayan-ba nyaji-ny | I fog camp-LOC see-PAST",
     "r130_perception_pronoun_fog_camp", 4, js(["ngayu", "ngurrbal", "bayan", "nyajil"]), js([]),
     "Pronoun A bare contrast for fog perception.", "0.84"),
    (31, "The man saw the mountain.",
     "Dingkar-angka manjal nyajin.",
     "dingkar-angka manjal nyaji-ny | man-ERG mountain see-PAST",
     "r130_perception_man_mountain", 4, js(["dingkar", "manjal", "nyajil"]), js([]),
     "Manjal mountain, not kulji; common-noun perceiver ERG.", "0.84"),
    (32, "We saw the mountain.",
     "Ngana manjal nyajin.",
     "ngana manjal nyaji-ny | we mountain see-PAST",
     "r130_perception_pronoun_mountain", 4, js(["ngana", "manjal", "nyajil"]), js([]),
     "Pronoun A bare contrast for mountain perception.", "0.84"),
    (33, "The woman saw the scrub.",
     "Jalbu-ngku madja nyajin.",
     "jalbu-ngku madja nyaji-ny | woman-ERG scrub see-PAST",
     "r130_perception_woman_scrub", 4, js(["jalbu", "madja", "nyajil"]), js([]),
     "Madja scrub perceived object; common-noun perceiver ERG.", "0.84"),
    (34, "I saw the scrub.",
     "Ngayu madja nyajin.",
     "ngayu madja nyaji-ny | I scrub see-PAST",
     "r130_perception_pronoun_scrub", 4, js(["ngayu", "madja", "nyajil"]), js([]),
     "Pronoun A bare contrast for scrub perception.", "0.84"),
    (35, "The child saw the flower on the tree.",
     "Karrkay-ngku nganka juku-ngu nyajin.",
     "karrkay-ngku nganka juku-ngu nyaji-ny | child-ERG flower tree-LOC see-PAST",
     "r130_perception_child_flower_tree", 4, js(["karrkay", "nganka", "juku", "nyajil"]), js([]),
     "Nganka flower plus sourced juku-ngu; common-noun perceiver ERG.", "0.84"),
    (36, "We saw the flower on the tree.",
     "Ngana nganka juku-ngu nyajin.",
     "ngana nganka juku-ngu nyaji-ny | we flower tree-LOC see-PAST",
     "r130_perception_pronoun_flower_tree", 4, js(["ngana", "nganka", "juku", "nyajil"]), js([]),
     "Pronoun A bare contrast for flower perception.", "0.84"),
    (37, "The man saw seeds in the bag.",
     "Dingkar-angka diburr balji-nga nyajin.",
     "dingkar-angka diburr balji-nga nyaji-ny | man-ERG seed bag-LOC see-PAST",
     "r130_perception_man_seed_bag", 4, js(["dingkar", "diburr", "balji", "nyajil"]), js([]),
     "Diburr seed sense selected; common-noun perceiver ERG.", "0.84"),
    (38, "I saw seeds in the bag.",
     "Ngayu diburr balji-nga nyajin.",
     "ngayu diburr balji-nga nyaji-ny | I seed bag-LOC see-PAST",
     "r130_perception_pronoun_seed_bag", 4, js(["ngayu", "diburr", "balji", "nyajil"]), js([]),
     "Pronoun A bare contrast for seed perception.", "0.84"),

    (39, "The man asked mother about water.",
     "Dingkar ngamu-ndu bana-ka babajin.",
     "dingkar ngamu-ndu bana-ka babaji-ny | man mother-LOC:pt water-DAT ask-PAST",
     "r130_ask_man_mother_water", 4, js(["dingkar", "ngamu", "bana", "babaji"]), js([]),
     "Sourced ask-about frame: ABS/S asker, person LOC:pt, topic DAT.", "0.86"),
    (40, "Grandmother asked grandfather about news.",
     "Babi kami-nda kuku-ku babajin.",
     "babi kami-nda kuku-ku babaji-ny | grandmother grandfather-LOC:pt news-DAT ask-PAST",
     "r130_ask_grandmother_grandfather_news", 4, js(["babi", "kami", "kuku", "babaji"]), js([]),
     "Sourced ask-about frame with retained kuku-ku DAT topic.", "0.86"),
    (41, "Mother asked grandmother about meat.",
     "Ngamu babi-nda minya-ka babajin.",
     "ngamu babi-nda minya-ka babaji-ny | mother grandmother-LOC:pt meat-DAT ask-PAST",
     "r130_ask_mother_grandmother_meat", 4, js(["ngamu", "babi", "minya", "babaji"]), js([]),
     "Sourced ask-about frame with retained minya-ka DAT topic.", "0.86"),
    (42, "Father asked the girl about the mango.",
     "Nganjan maral-anda mayngku-ku babajin.",
     "nganjan maral-anda mayngku-ku babaji-ny | father girl-LOC:pt mango-DAT ask-PAST",
     "r130_ask_father_girl_mango", 4, js(["nganjan", "maral", "mayngku", "babaji"]), js(["mayngku"]),
     "Sourced ask-about frame; mayngku loan/contact topic logged.", "0.86"),
    (43, "The girl asked grandfather about water.",
     "Maral kami-nda bana-ka babajin.",
     "maral kami-nda bana-ka babaji-ny | girl grandfather-LOC:pt water-DAT ask-PAST",
     "r130_ask_girl_grandfather_water", 4, js(["maral", "kami", "bana", "babaji"]), js([]),
     "Sourced ask-about frame with retained bana-ka DAT topic.", "0.86"),

    (44, "The man laughed at mother.",
     "Dingkar ngamu-ndu yajarrin.",
     "dingkar ngamu-ndu yajarri-ny | man mother-DAT:pt laugh-PAST",
     "r130_laugh_man_mother", 3, js(["dingkar", "ngamu", "yajarril"]), js([]),
     "Retained yajarri-l laugh-target frame with sourced DAT:pt target.", "0.84"),
    (45, "The woman laughed at the girl.",
     "Jalbu maral-anda yajarrin.",
     "jalbu maral-anda yajarri-ny | woman girl-DAT:pt laugh-PAST",
     "r130_laugh_woman_girl", 3, js(["jalbu", "maral", "yajarril"]), js([]),
     "Retained yajarri-l laugh-target frame with sourced DAT:pt target.", "0.84"),
    (46, "The young man laughed at grandfather.",
     "Warru kami-nda yajarrin.",
     "warru kami-nda yajarri-ny | young.man grandfather-DAT:pt laugh-PAST",
     "r130_laugh_young_man_grandfather", 3, js(["warru", "kami", "yajarril"]), js([]),
     "Retained yajarri-l laugh-target frame with sourced DAT:pt target.", "0.84"),
    (47, "The child laughed at grandmother.",
     "Karrkay babi-nda yajarrin.",
     "karrkay babi-nda yajarri-ny | child grandmother-DAT:pt laugh-PAST",
     "r130_laugh_child_grandmother", 3, js(["karrkay", "babi", "yajarril"]), js([]),
     "Retained yajarri-l laugh-target frame with sourced DAT:pt target.", "0.84"),
    (48, "Grandmother laughed at father.",
     "Babi nganjan-anda yajarrin.",
     "babi nganjan-anda yajarri-ny | grandmother father-DAT:pt laugh-PAST",
     "r130_laugh_grandmother_father", 3, js(["babi", "nganjan", "yajarril"]), js([]),
     "Retained yajarri-l laugh-target frame with sourced DAT:pt target.", "0.84"),

    (49, "Mother went to the mountain with the baby.",
     "Ngamu ngawa-nji manjal-ba dungan.",
     "ngamu ngawa-nji manjal-ba dunga-ny | mother baby-COMIT:pt mountain-LOC go-PAST",
     "r130_comit_mother_baby_mountain", 4, js(["ngamu", "ngawa", "manjal", "dungay"]), js([]),
     "Ngawa-nji closed comitative; manjal-ba retained LOC.", "0.84"),
    (50, "The old man went to the mountain with a stick.",
     "Wulman juku-ji manjal-ba dungan.",
     "wulman juku-ji manjal-ba dunga-ny | old.man stick-COMIT mountain-LOC go-PAST",
     "r130_comit_old_man_stick_mountain", 4, js(["wulman", "juku", "manjal", "dungay"]), js(["wulman"]),
     "Juku-ji closed sourced comitative; wulman contact form logged.", "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("r130_"):
            issues.append(f"{label}: Rule 130 batch frame must start with r130_")
        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}: construction 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 = [
            ("leaf", "birra"),
            ("leaves", "birra"),
            ("bark", "dumbul"),
            ("smoke", "kubu"),
            ("stone", "kulji"),
            ("sand", "jukar"),
            ("mountain", "manjal"),
            ("scrub", "madja"),
            ("seed", "diburr"),
            ("seeds", "diburr"),
            ("flower", "nganka"),
            ("fog", "ngurrbal"),
        ]
        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, "birra") and "leaf" not in analysis_low:
            issues.append(f"{label}: birra must be glossed leaf, not lungs")
        if has_token(low, "dumbul") and not any(word in analysis_low for word in ("bark", "covering")):
            issues.append(f"{label}: dumbul must be glossed bark/hard covering")
        if has_token(low, "diburr") and "seed" not in analysis_low:
            issues.append(f"{label}: diburr must use the seed sense in this batch")
        if has_token(low, "kulji") and not any(word in analysis_low for word in ("stone", "rock")):
            issues.append(f"{label}: kulji must be glossed stone/rock")
        if "mountain" in english_low and has_token(low, "kulji"):
            issues.append(f"{label}: English mountain must use manjal, not kulji")
        if "kulji-bu" in low:
            issues.append(f"{label}: no kulji-bu instrument in Rule 130")
        if "INST" in analysis:
            issues.append(f"{label}: no instrument analysis in Rule 130 construction consolidation")
        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 130 draft: construction consolidation after Rule 129", "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 130 source pass rechecked dictionary.yaml, Patz grammar, existing corpus lexemes, and planned-surface "
            "duplicates before authoring. No new lexical heads were admitted; Rule 129 heads were drilled in old frames."
        ),
        command="rg dictionary.yaml and grammar.md; sqlite lexeme readback; exact duplicate scan over 50 planned rows",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="dictionary-source-check",
        actor="claude-main",
        detail=(
            "Dictionary controls retained birra leaf, dumbul bark/hard covering, kubu smoke, kulji pebbles/small stones, "
            "jukar sand, madja scrub/rainforest, manjal mountain, diburr seed/egg with seed selected, nganka flower, "
            "ngurrbal fog, and old person/topic/place heads."
        ),
        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/corpus controls retained kulji/kulji-nga and the not-mountain warning, manjal-ba/manjal-muny, "
            "bayan-ka/bayan-muny, bubu-ngu, wabarr-ba, balji-nga, baral-ba, ngalkal-ba, juku-ngu, madja-nga, "
            "person LOC:pt/DAT:pt forms, closed comitatives, and old predicates."
        ),
        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 lexical heads; birra leaf not lungs; dumbul bark only; diburr seed only; kulji stone/rock "
            "not mountain; no kulji-bu or other instrument rows; warrur excluded; wulman/mayngku 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="Final planned-surface scan found 50 planned rows, 50 unique within-batch surfaces, and zero exact cross-corpus duplicates.",
        command="sqlite exact-surface query over planned Batch 172 rows",
        output_excerpt="planned 50 unique 50; no duplicate lines emitted",
        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 172 stores source inventory, static guards, duplicate scan, 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 130 construction rows under_review after static guards and duplicate checks.",
        command="python3 batch_scripts/bank_172.py",
        artifact_path="batch_scripts/bank_172.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="bank",
        event_type="row-inventory",
        actor="claude-main",
        detail=(
            "Rows 1-10 rest/come/stand/place; 11-20 placement/leave/transfer; 21-38 perception; "
            "39-43 ask-about; 44-48 laugh targets; 49-50 closed comitatives."
        ),
        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())
