#!/usr/bin/env python3
"""Bank batch-192: Rule 150 construction consolidation after Rule 149."""

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

TARGET_HEADS = {
    "kalka": "spear",
    "naybu": "knife",
    "waymbil": "axe",
    "karra": "rope",
    "makarr": "fish.net",
    "yinba": "fish.spear",
    "balur": "spear-thrower",
    "kulji": "stone",
    "juku": "wood",
    "juwal": "digging.stick",
}
SUPPORT_FORMS = {"madja-nga", "ngalkal-ba", "bayan-ba", "bubu-ngu"}
PRONOUN_A = {"ngayu", "ngana", "jana"}
COMMON_A = {"ngamu-ngku", "nganjan-angka", "babi-ngka", "karrkay-ngku", "kami-ngka", "jalbu-ngku", "dingkar-angka"}
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",
}
DENY_ENGLISH = (
    "speared", "spearing", "cut", "cutting", "sharpen", "sharpened", "scrape", "scraped", "hit", "hitting",
    "kill", "killed", "catch", "caught", "netted", "threw", "throwing", "poke", "poked", "tie", "tied",
    "make", "made", "wound", "blood", "dead", "hunting", "fish with", "tree", "yam", "fruit", "honey",
)


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 spear is on the open ground.", "Kalka ngalkal-ba.",
        "kalka ngalkal-ba | spear open.ground-LOC", "r150_location_spear_open", ["kalka", "ngalkal"], "Rule 150 retained target with support locative ngalkal-ba."),
    row(2, "The knife is on the ground.", "Naybu bubu-ngu.",
        "naybu bubu-ngu | knife ground-LOC", "r150_location_knife_ground", ["naybu", "bubu"], "Rule 150 retained target with support locative bubu-ngu."),
    row(3, "The axe is on the open ground.", "Waymbil ngalkal-ba.",
        "waymbil ngalkal-ba | axe open.ground-LOC", "r150_location_axe_open", ["waymbil", "ngalkal"], "Rule 150 retained target with support locative ngalkal-ba."),
    row(4, "The rope is at the camp.", "Karra bayan-ba.",
        "karra bayan-ba | rope camp-LOC", "r150_location_rope_camp", ["karra", "bayan"], "Rule 150 retained target with support locative bayan-ba."),
    row(5, "The fish net is on the ground.", "Makarr bubu-ngu.",
        "makarr bubu-ngu | fish.net ground-LOC", "r150_location_net_ground", ["makarr", "bubu"], "Rule 150 retained target with support locative bubu-ngu."),
    row(6, "The fish spear is on the open ground.", "Yinba ngalkal-ba.",
        "yinba ngalkal-ba | fish.spear open.ground-LOC", "r150_location_fish_spear_open", ["yinba", "ngalkal"], "Rule 150 retained target with support locative ngalkal-ba."),
    row(7, "The spear-thrower is on the ground.", "Balur bubu-ngu.",
        "balur bubu-ngu | spear-thrower ground-LOC", "r150_location_spear_thrower_ground", ["balur", "bubu"], "Rule 150 retained target with support locative bubu-ngu."),
    row(8, "The stone is at the camp.", "Kulji bayan-ba.",
        "kulji bayan-ba | stone camp-LOC", "r150_location_stone_camp", ["kulji", "bayan"], "Rule 150 retained target with support locative bayan-ba."),
    row(9, "The wood is on the ground.", "Juku bubu-ngu.",
        "juku bubu-ngu | wood ground-LOC", "r150_location_wood_ground", ["juku", "bubu"], "Rule 150 selected wood/material sense with support locative bubu-ngu."),
    row(10, "The digging stick is at the camp.", "Juwal bayan-ba.",
        "juwal bayan-ba | digging.stick camp-LOC", "r150_location_digging_stick_camp", ["juwal", "bayan"], "Rule 150 selected digging-stick sense with support locative bayan-ba."),
    row(11, "I saw the knife.", "Ngayu naybu nyajin.",
        "ngayu naybu nyaji-ny | I knife see-PAST", "r150_perception_i_knife", ["ngayu", "naybu", "nyaji-l"], "Pronoun A bare; retained knife object."),
    row(12, "We saw the axe.", "Ngana waymbil nyajin.",
        "ngana waymbil nyaji-ny | we axe see-PAST", "r150_perception_we_axe", ["ngana", "waymbil", "nyaji-l"], "Pronoun A bare; retained axe object."),
    row(13, "They saw the rope.", "Jana karra nyajin.",
        "jana karra nyaji-ny | they rope see-PAST", "r150_perception_they_rope", ["jana", "karra", "nyaji-l"], "Pronoun A bare; retained rope object."),
    row(14, "Mother saw the fish net.", "Ngamu-ngku makarr nyajin.",
        "ngamu-ngku makarr nyaji-ny | mother-ERG fish.net see-PAST", "r150_perception_mother_net", ["ngamu", "makarr", "nyaji-l"], "Common-noun A ERG; retained fish-net object."),
    row(15, "Father saw the fish spear.", "Nganjan-angka yinba nyajin.",
        "nganjan-angka yinba nyaji-ny | father-ERG fish.spear see-PAST", "r150_perception_father_fish_spear", ["nganjan", "yinba", "nyaji-l"], "Common-noun A ERG; retained fish-spear object."),
    row(16, "The child saw the spear-thrower.", "Karrkay-ngku balur nyajin.",
        "karrkay-ngku balur nyaji-ny | child-ERG spear-thrower see-PAST", "r150_perception_child_spear_thrower", ["karrkay", "balur", "nyaji-l"], "Common-noun A ERG; retained spear-thrower object."),
    row(17, "Grandfather saw the stone.", "Kami-ngka kulji nyajin.",
        "kami-ngka kulji nyaji-ny | grandfather-ERG stone see-PAST", "r150_perception_grandfather_stone", ["kami", "kulji", "nyaji-l"], "Common-noun A ERG; retained stone object."),
    row(18, "The woman saw the wood.", "Jalbu-ngku juku nyajin.",
        "jalbu-ngku juku nyaji-ny | woman-ERG wood see-PAST", "r150_perception_woman_wood", ["jalbu", "juku", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(19, "The man saw the digging stick.", "Dingkar-angka juwal nyajin.",
        "dingkar-angka juwal nyaji-ny | man-ERG digging.stick see-PAST", "r150_perception_man_digging_stick", ["dingkar", "juwal", "nyaji-l"], "Common-noun A ERG; selected digging-stick sense."),
    row(20, "Grandmother saw the spear.", "Babi-ngka kalka nyajin.",
        "babi-ngka kalka nyaji-ny | grandmother-ERG spear see-PAST", "r150_perception_grandmother_spear", ["babi", "kalka", "nyaji-l"], "Common-noun A ERG; retained spear object."),
    row(21, "I saw the knife on the ground.", "Ngayu naybu bubu-ngu nyajin.",
        "ngayu naybu bubu-ngu nyaji-ny | I knife ground-LOC see-PAST", "r150_perception_i_knife_ground", ["ngayu", "naybu", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(22, "We saw the axe on the open ground.", "Ngana waymbil ngalkal-ba nyajin.",
        "ngana waymbil ngalkal-ba nyaji-ny | we axe open.ground-LOC see-PAST", "r150_perception_we_axe_open", ["ngana", "waymbil", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(23, "They saw the rope at the camp.", "Jana karra bayan-ba nyajin.",
        "jana karra bayan-ba nyaji-ny | they rope camp-LOC see-PAST", "r150_perception_they_rope_camp", ["jana", "karra", "bayan", "nyaji-l"], "Pronoun A bare; support locative bayan-ba."),
    row(24, "Mother saw the fish net on the ground.", "Ngamu-ngku makarr bubu-ngu nyajin.",
        "ngamu-ngku makarr bubu-ngu nyaji-ny | mother-ERG fish.net ground-LOC see-PAST", "r150_perception_mother_net_ground", ["ngamu", "makarr", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(25, "Father saw the fish spear on the open ground.", "Nganjan-angka yinba ngalkal-ba nyajin.",
        "nganjan-angka yinba ngalkal-ba nyaji-ny | father-ERG fish.spear open.ground-LOC see-PAST", "r150_perception_father_fish_spear_open", ["nganjan", "yinba", "ngalkal", "nyaji-l"], "Common-noun A ERG; support locative ngalkal-ba."),
    row(26, "The child saw the spear-thrower on the ground.", "Karrkay-ngku balur bubu-ngu nyajin.",
        "karrkay-ngku balur bubu-ngu nyaji-ny | child-ERG spear-thrower ground-LOC see-PAST", "r150_perception_child_spear_thrower_ground", ["karrkay", "balur", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(27, "Grandfather saw the stone at the camp.", "Kami-ngka kulji bayan-ba nyajin.",
        "kami-ngka kulji bayan-ba nyaji-ny | grandfather-ERG stone camp-LOC see-PAST", "r150_perception_grandfather_stone_camp", ["kami", "kulji", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(28, "The woman saw the wood on the ground.", "Jalbu-ngku juku bubu-ngu nyajin.",
        "jalbu-ngku juku bubu-ngu nyaji-ny | woman-ERG wood ground-LOC see-PAST", "r150_perception_woman_wood_ground", ["jalbu", "juku", "bubu", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(29, "The man saw the digging stick at the camp.", "Dingkar-angka juwal bayan-ba nyajin.",
        "dingkar-angka juwal bayan-ba nyaji-ny | man-ERG digging.stick camp-LOC see-PAST", "r150_perception_man_digging_stick_camp", ["dingkar", "juwal", "bayan", "nyaji-l"], "Common-noun A ERG; selected digging-stick sense."),
    row(30, "Grandmother saw the spear on the open ground.", "Babi-ngka kalka ngalkal-ba nyajin.",
        "babi-ngka kalka ngalkal-ba nyaji-ny | grandmother-ERG spear open.ground-LOC see-PAST", "r150_perception_grandmother_spear_open", ["babi", "kalka", "ngalkal", "nyaji-l"], "Common-noun A ERG; support locative ngalkal-ba."),
    row(31, "I saw the axe at the camp.", "Ngayu waymbil bayan-ba nyajin.",
        "ngayu waymbil bayan-ba nyaji-ny | I axe camp-LOC see-PAST", "r150_perception_i_axe_camp", ["ngayu", "waymbil", "bayan", "nyaji-l"], "Pronoun A bare; support locative bayan-ba."),
    row(32, "We saw the rope on the ground.", "Ngana karra bubu-ngu nyajin.",
        "ngana karra bubu-ngu nyaji-ny | we rope ground-LOC see-PAST", "r150_perception_we_rope_ground", ["ngana", "karra", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(33, "They saw the fish net on the ground.", "Jana makarr bubu-ngu nyajin.",
        "jana makarr bubu-ngu nyaji-ny | they fish.net ground-LOC see-PAST", "r150_perception_they_net_ground", ["jana", "makarr", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(34, "Mother saw the fish spear on the open ground.", "Ngamu-ngku yinba ngalkal-ba nyajin.",
        "ngamu-ngku yinba ngalkal-ba nyaji-ny | mother-ERG fish.spear open.ground-LOC see-PAST", "r150_perception_mother_fish_spear_open", ["ngamu", "yinba", "ngalkal", "nyaji-l"], "Common-noun A ERG; support locative ngalkal-ba."),
    row(35, "Father saw the spear-thrower on the ground.", "Nganjan-angka balur bubu-ngu nyajin.",
        "nganjan-angka balur bubu-ngu nyaji-ny | father-ERG spear-thrower ground-LOC see-PAST", "r150_perception_father_spear_thrower_ground", ["nganjan", "balur", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(36, "The child saw the stone at the camp.", "Karrkay-ngku kulji bayan-ba nyajin.",
        "karrkay-ngku kulji bayan-ba nyaji-ny | child-ERG stone camp-LOC see-PAST", "r150_perception_child_stone_camp", ["karrkay", "kulji", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(37, "Grandfather saw the wood on the ground.", "Kami-ngka juku bubu-ngu nyajin.",
        "kami-ngka juku bubu-ngu nyaji-ny | grandfather-ERG wood ground-LOC see-PAST", "r150_perception_grandfather_wood_ground", ["kami", "juku", "bubu", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(38, "The woman saw the digging stick at the camp.", "Jalbu-ngku juwal bayan-ba nyajin.",
        "jalbu-ngku juwal bayan-ba nyaji-ny | woman-ERG digging.stick camp-LOC see-PAST", "r150_perception_woman_digging_stick_camp", ["jalbu", "juwal", "bayan", "nyaji-l"], "Common-noun A ERG; selected digging-stick sense."),
    row(39, "The man saw the knife on the ground.", "Dingkar-angka naybu bubu-ngu nyajin.",
        "dingkar-angka naybu bubu-ngu nyaji-ny | man-ERG knife ground-LOC see-PAST", "r150_perception_man_knife_ground", ["dingkar", "naybu", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(40, "Grandmother saw the axe on the open ground.", "Babi-ngka waymbil ngalkal-ba nyajin.",
        "babi-ngka waymbil ngalkal-ba nyaji-ny | grandmother-ERG axe open.ground-LOC see-PAST", "r150_perception_grandmother_axe_open", ["babi", "waymbil", "ngalkal", "nyaji-l"], "Common-noun A ERG; support locative ngalkal-ba."),
    row(41, "I see the knife.", "Ngayu naybu nyajil.",
        "ngayu naybu nyaji-l | I knife see-NONPAST", "r150_present_i_knife", ["ngayu", "naybu", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(42, "We see the axe.", "Ngana waymbil nyajil.",
        "ngana waymbil nyaji-l | we axe see-NONPAST", "r150_present_we_axe", ["ngana", "waymbil", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(43, "They see the rope.", "Jana karra nyajil.",
        "jana karra nyaji-l | they rope see-NONPAST", "r150_present_they_rope", ["jana", "karra", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(44, "Mother sees the fish net.", "Ngamu-ngku makarr nyajil.",
        "ngamu-ngku makarr nyaji-l | mother-ERG fish.net see-NONPAST", "r150_present_mother_net", ["ngamu", "makarr", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(45, "Father sees the fish spear.", "Nganjan-angka yinba nyajil.",
        "nganjan-angka yinba nyaji-l | father-ERG fish.spear see-NONPAST", "r150_present_father_fish_spear", ["nganjan", "yinba", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(46, "The child sees the spear-thrower.", "Karrkay-ngku balur nyajil.",
        "karrkay-ngku balur nyaji-l | child-ERG spear-thrower see-NONPAST", "r150_present_child_spear_thrower", ["karrkay", "balur", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(47, "Grandfather sees the stone.", "Kami-ngka kulji nyajil.",
        "kami-ngka kulji nyaji-l | grandfather-ERG stone see-NONPAST", "r150_present_grandfather_stone", ["kami", "kulji", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(48, "The woman sees the wood.", "Jalbu-ngku juku nyajil.",
        "jalbu-ngku juku nyaji-l | woman-ERG wood see-NONPAST", "r150_present_woman_wood", ["jalbu", "juku", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(49, "The man sees the digging stick.", "Dingkar-angka juwal nyajil.",
        "dingkar-angka juwal nyaji-l | man-ERG digging.stick see-NONPAST", "r150_present_man_digging_stick", ["dingkar", "juwal", "nyaji-l"], "Common-noun A ERG; selected digging-stick sense."),
    row(50, "Grandmother sees the spear.", "Babi-ngka kalka nyajil.",
        "babi-ngka kalka nyaji-l | grandmother-ERG spear see-NONPAST", "r150_present_grandmother_spear", ["babi", "kalka", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
]


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|bu|ji|jirr|ku|mundu|amu|mu)\b", 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()
    support_to_head = {"madja-nga": "madja", "ngalkal-ba": "ngalkal", "bayan-ba": "bayan", "bubu-ngu": "bubu"}
    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("r150_"):
            issues.append(f"{label}: Rule 150 frame must start with r150_")
        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 150")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied action/ecology 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 150 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 has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        for form in re.findall(r"\b[a-z]+-(?:nga|ba|muny|ngu)\b", low):
            if form not in SUPPORT_FORMS:
                issues.append(f"{label}: unapproved support local form {form}")
        for support, head in support_to_head.items():
            if has_token(low, support) and head not in words:
                issues.append(f"{label}: support head {head} missing from words_used")
        checks = {
            "kalka": "spear",
            "naybu": "knife",
            "waymbil": "axe",
            "karra": "rope",
            "makarr": "fish net",
            "yinba": "fish spear",
            "balur": "spear-thrower",
            "kulji": "stone",
            "juku": "wood",
            "juwal": "digging stick",
        }
        for head, english_marker in checks.items():
            if has_token(low, head) and english_marker not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {english_marker!r}")
        if re.search(r"\b[a-z]+-bu\b", low) or "INST" in analysis:
            issues.append(f"{label}: no instrument morphology in Rule 150")
        if any(bad in english_low for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied action/use/polysemy field in English")
        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 "nyajil" in low and "see-NONPAST" not in analysis:
            issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        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 150 draft: construction consolidation after Rule 149", "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 150 source pass admitted no new target heads. It retained Rule 149 implement/material names and "
            "source-checked support/perception forms: madja-nga, ngalkal-ba, bayan-ba, bubu-ngu, nyaji-ny past, and "
            "nyaji-l nonpast. Dictionary, grammar, lexeme-table, and corpus-surface readback completed."
        ),
        command="dictionary.yaml readback; grammar.md exact occurrence readback; sqlite lexeme and duplicate readback",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail=(
            "Rule 150 consolidates Rule 149 implement/material heads in support-location and perception frames only. "
            "It excludes cutting, spearing, sharpening, hitting, catching, throwing, tying, making, scraping, poking, "
            "killing, fish-catch, hunting, wound, blood, dead, target case forms, instrument morphology, compounds, "
            "possessives, juku tree ecology, juwal yam sense, and cultural/weapon-use inference."
        ),
        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_192.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 retained implement/material target per row, selected English senses enforced, no action/use/polysemy field, no instruments, no target case forms, approved support locatives only, common-noun A ERG, and pronoun A bare.",
        command="python3 batch_scripts/bank_192.py static scan",
        artifact_path="batch_scripts/bank_192.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 150 implement/material construction-consolidation rows.",
        command="python3 batch_scripts/bank_192.py",
        artifact_path="batch_scripts/bank_192.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())
