#!/usr/bin/env python3
"""Bank batch-191: Rule 149 implements/materials lexical expansion after Rule 148."""

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-191"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-191-implements-materials-lexical-expansion-after-rule148-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",
}
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", "weapon action", "wound", "blood", "dead", "hunting", "fish with",
)


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 ground.", "Kalka bubu-ngu.",
        "kalka bubu-ngu | spear ground-LOC", "r149_location_spear_ground", ["kalka", "bubu"], "Patz has kalka 'spear' and bubu-ngu ground/place LOC; lexical state/location only."),
    row(2, "The knife is good.", "Naybu ngulkurr.",
        "naybu ngulkurr | knife good", "r149_state_knife_good", ["naybu", "ngulkurr"], "Dictionary and Patz list naybu 'knife'; ngulkurr predicate established."),
    row(3, "The axe is blunt.", "Waymbil dudu.",
        "waymbil dudu | axe blunt", "r149_state_axe_blunt", ["waymbil", "dudu"], "Dictionary lists waymbil 'axe'; Patz supports dudu 'blunt'."),
    row(4, "The rope is big.", "Karra yalbay.",
        "karra yalbay | rope big", "r149_state_rope_big", ["karra", "yalbay"], "Patz ex.(197) karra rope; yalbay predicate established."),
    row(5, "The fish net is big.", "Makarr yalbay.",
        "makarr yalbay | fish.net big", "r149_state_net_big", ["makarr", "yalbay"], "Patz ex.(162) makarr net; yalbay predicate established."),
    row(6, "The fish spear is blunt.", "Yinba dudu.",
        "yinba dudu | fish.spear blunt", "r149_state_fish_spear_blunt", ["yinba", "dudu"], "Dictionary/Patz support yinba fish spear; dudu blunt predicate."),
    row(7, "The spear-thrower is good.", "Balur ngulkurr.",
        "balur ngulkurr | spear-thrower good", "r149_state_spear_thrower_good", ["balur", "ngulkurr"], "Dictionary has balur spear thrower; ngulkurr predicate established."),
    row(8, "The stone is good.", "Kulji ngulkurr.",
        "kulji ngulkurr | stone good", "r149_state_stone_good", ["kulji", "ngulkurr"], "Patz has kulji stone/rock; ngulkurr predicate established."),
    row(9, "The wood is big.", "Juku yalbay.",
        "juku yalbay | wood big", "r149_state_wood_big", ["juku", "yalbay"], "Dictionary/Patz support juku tree/wood; English selects wood/material sense."),
    row(10, "The digging stick is big.", "Juwal yalbay.",
        "juwal yalbay | digging.stick big", "r149_state_digging_stick_big", ["juwal", "yalbay"], "Patz ex.(629) juwal-da digging stick; dictionary gives yam/digging-stick polysemy, selected here as implement."),
    row(11, "The spear is at the camp.", "Kalka bayan-ba.",
        "kalka bayan-ba | spear camp-LOC", "r149_location_spear_camp", ["kalka", "bayan"], "Target plus support locative bayan-ba only."),
    row(12, "The knife is at the camp.", "Naybu bayan-ba.",
        "naybu bayan-ba | knife camp-LOC", "r149_location_knife_camp", ["naybu", "bayan"], "Target plus support locative bayan-ba only."),
    row(13, "The axe is at the camp.", "Waymbil bayan-ba.",
        "waymbil bayan-ba | axe camp-LOC", "r149_location_axe_camp", ["waymbil", "bayan"], "Target plus support locative bayan-ba only."),
    row(14, "The rope is on the ground.", "Karra bubu-ngu.",
        "karra bubu-ngu | rope ground-LOC", "r149_location_rope_ground", ["karra", "bubu"], "Target plus support locative bubu-ngu only."),
    row(15, "The fish net is on the open ground.", "Makarr ngalkal-ba.",
        "makarr ngalkal-ba | fish.net open.ground-LOC", "r149_location_net_open", ["makarr", "ngalkal"], "Target plus support locative ngalkal-ba only."),
    row(16, "The fish spear is at the camp.", "Yinba bayan-ba.",
        "yinba bayan-ba | fish.spear camp-LOC", "r149_location_fish_spear_camp", ["yinba", "bayan"], "Target plus support locative bayan-ba only."),
    row(17, "The spear-thrower is at the camp.", "Balur bayan-ba.",
        "balur bayan-ba | spear-thrower camp-LOC", "r149_location_spear_thrower_camp", ["balur", "bayan"], "Target plus support locative bayan-ba only."),
    row(18, "The stone is on the open ground.", "Kulji ngalkal-ba.",
        "kulji ngalkal-ba | stone open.ground-LOC", "r149_location_stone_open", ["kulji", "ngalkal"], "Target plus support locative ngalkal-ba only."),
    row(19, "The wood is in the scrub.", "Juku madja-nga.",
        "juku madja-nga | wood scrub-LOC", "r149_location_wood_scrub", ["juku", "madja"], "Target plus support locative madja-nga only."),
    row(20, "The digging stick is on the ground.", "Juwal bubu-ngu.",
        "juwal bubu-ngu | digging.stick ground-LOC", "r149_location_digging_stick_ground", ["juwal", "bubu"], "Selected juwal implement sense plus support locative bubu-ngu."),
    row(21, "Mother saw the spear.", "Ngamu-ngku kalka nyajin.",
        "ngamu-ngku kalka nyaji-ny | mother-ERG spear see-PAST", "r149_perception_mother_spear", ["ngamu", "kalka", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(22, "Father saw the knife.", "Nganjan-angka naybu nyajin.",
        "nganjan-angka naybu nyaji-ny | father-ERG knife see-PAST", "r149_perception_father_knife", ["nganjan", "naybu", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(23, "The child saw the axe.", "Karrkay-ngku waymbil nyajin.",
        "karrkay-ngku waymbil nyaji-ny | child-ERG axe see-PAST", "r149_perception_child_axe", ["karrkay", "waymbil", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(24, "Grandfather saw the rope.", "Kami-ngka karra nyajin.",
        "kami-ngka karra nyaji-ny | grandfather-ERG rope see-PAST", "r149_perception_grandfather_rope", ["kami", "karra", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(25, "The woman saw the fish net.", "Jalbu-ngku makarr nyajin.",
        "jalbu-ngku makarr nyaji-ny | woman-ERG fish.net see-PAST", "r149_perception_woman_net", ["jalbu", "makarr", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(26, "The man saw the fish spear.", "Dingkar-angka yinba nyajin.",
        "dingkar-angka yinba nyaji-ny | man-ERG fish.spear see-PAST", "r149_perception_man_fish_spear", ["dingkar", "yinba", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(27, "Grandmother saw the spear-thrower.", "Babi-ngka balur nyajin.",
        "babi-ngka balur nyaji-ny | grandmother-ERG spear-thrower see-PAST", "r149_perception_grandmother_spear_thrower", ["babi", "balur", "nyaji-l"], "Common-noun A ERG; target object bare."),
    row(28, "I saw the stone.", "Ngayu kulji nyajin.",
        "ngayu kulji nyaji-ny | I stone see-PAST", "r149_perception_i_stone", ["ngayu", "kulji", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(29, "We saw the wood.", "Ngana juku nyajin.",
        "ngana juku nyaji-ny | we wood see-PAST", "r149_perception_we_wood", ["ngana", "juku", "nyaji-l"], "Pronoun A bare; selected wood/material sense."),
    row(30, "They saw the digging stick.", "Jana juwal nyajin.",
        "jana juwal nyaji-ny | they digging.stick see-PAST", "r149_perception_they_digging_stick", ["jana", "juwal", "nyaji-l"], "Pronoun A bare; selected juwal implement sense."),
    row(31, "I saw the spear at the camp.", "Ngayu kalka bayan-ba nyajin.",
        "ngayu kalka bayan-ba nyaji-ny | I spear camp-LOC see-PAST", "r149_perception_i_spear_camp", ["ngayu", "kalka", "bayan", "nyaji-l"], "Pronoun A bare; target plus support locative."),
    row(32, "We saw the knife at the camp.", "Ngana naybu bayan-ba nyajin.",
        "ngana naybu bayan-ba nyaji-ny | we knife camp-LOC see-PAST", "r149_perception_we_knife_camp", ["ngana", "naybu", "bayan", "nyaji-l"], "Pronoun A bare; target plus support locative."),
    row(33, "They saw the axe at the camp.", "Jana waymbil bayan-ba nyajin.",
        "jana waymbil bayan-ba nyaji-ny | they axe camp-LOC see-PAST", "r149_perception_they_axe_camp", ["jana", "waymbil", "bayan", "nyaji-l"], "Pronoun A bare; target plus support locative."),
    row(34, "Mother saw the rope on the ground.", "Ngamu-ngku karra bubu-ngu nyajin.",
        "ngamu-ngku karra bubu-ngu nyaji-ny | mother-ERG rope ground-LOC see-PAST", "r149_perception_mother_rope_ground", ["ngamu", "karra", "bubu", "nyaji-l"], "Common-noun A ERG; target plus support locative."),
    row(35, "Father saw the fish net on the open ground.", "Nganjan-angka makarr ngalkal-ba nyajin.",
        "nganjan-angka makarr ngalkal-ba nyaji-ny | father-ERG fish.net open.ground-LOC see-PAST", "r149_perception_father_net_open", ["nganjan", "makarr", "ngalkal", "nyaji-l"], "Common-noun A ERG; target plus support locative."),
    row(36, "The child saw the fish spear at the camp.", "Karrkay-ngku yinba bayan-ba nyajin.",
        "karrkay-ngku yinba bayan-ba nyaji-ny | child-ERG fish.spear camp-LOC see-PAST", "r149_perception_child_fish_spear_camp", ["karrkay", "yinba", "bayan", "nyaji-l"], "Common-noun A ERG; target plus support locative."),
    row(37, "Grandfather saw the spear-thrower at the camp.", "Kami-ngka balur bayan-ba nyajin.",
        "kami-ngka balur bayan-ba nyaji-ny | grandfather-ERG spear-thrower camp-LOC see-PAST", "r149_perception_grandfather_spear_thrower_camp", ["kami", "balur", "bayan", "nyaji-l"], "Common-noun A ERG; target plus support locative."),
    row(38, "The woman saw the stone on the ground.", "Jalbu-ngku kulji bubu-ngu nyajin.",
        "jalbu-ngku kulji bubu-ngu nyaji-ny | woman-ERG stone ground-LOC see-PAST", "r149_perception_woman_stone_ground", ["jalbu", "kulji", "bubu", "nyaji-l"], "Common-noun A ERG; target plus support locative."),
    row(39, "The man saw the wood in the scrub.", "Dingkar-angka juku madja-nga nyajin.",
        "dingkar-angka juku madja-nga nyaji-ny | man-ERG wood scrub-LOC see-PAST", "r149_perception_man_wood_scrub", ["dingkar", "juku", "madja", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(40, "Grandmother saw the digging stick on the ground.", "Babi-ngka juwal bubu-ngu nyajin.",
        "babi-ngka juwal bubu-ngu nyaji-ny | grandmother-ERG digging.stick ground-LOC see-PAST", "r149_perception_grandmother_digging_stick_ground", ["babi", "juwal", "bubu", "nyaji-l"], "Common-noun A ERG; selected juwal implement sense."),
    row(41, "I see the spear.", "Ngayu kalka nyajil.",
        "ngayu kalka nyaji-l | I spear see-NONPAST", "r149_present_i_spear", ["ngayu", "kalka", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(42, "We see the knife.", "Ngana naybu nyajil.",
        "ngana naybu nyaji-l | we knife see-NONPAST", "r149_present_we_knife", ["ngana", "naybu", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(43, "They see the axe.", "Jana waymbil nyajil.",
        "jana waymbil nyaji-l | they axe see-NONPAST", "r149_present_they_axe", ["jana", "waymbil", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(44, "Mother sees the rope.", "Ngamu-ngku karra nyajil.",
        "ngamu-ngku karra nyaji-l | mother-ERG rope see-NONPAST", "r149_present_mother_rope", ["ngamu", "karra", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(45, "Father sees the fish net.", "Nganjan-angka makarr nyajil.",
        "nganjan-angka makarr nyaji-l | father-ERG fish.net see-NONPAST", "r149_present_father_net", ["nganjan", "makarr", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(46, "The child sees the fish spear.", "Karrkay-ngku yinba nyajil.",
        "karrkay-ngku yinba nyaji-l | child-ERG fish.spear see-NONPAST", "r149_present_child_fish_spear", ["karrkay", "yinba", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(47, "Grandfather sees the spear-thrower.", "Kami-ngka balur nyajil.",
        "kami-ngka balur nyaji-l | grandfather-ERG spear-thrower see-NONPAST", "r149_present_grandfather_spear_thrower", ["kami", "balur", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(48, "The woman sees the stone.", "Jalbu-ngku kulji nyajil.",
        "jalbu-ngku kulji nyaji-l | woman-ERG stone see-NONPAST", "r149_present_woman_stone", ["jalbu", "kulji", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(49, "The man sees the wood.", "Dingkar-angka juku nyajil.",
        "dingkar-angka juku nyaji-l | man-ERG wood see-NONPAST", "r149_present_man_wood", ["dingkar", "juku", "nyaji-l"], "Common-noun A ERG; selected wood/material sense."),
    row(50, "Grandmother sees the digging stick.", "Babi-ngka juwal nyajil.",
        "babi-ngka juwal nyaji-l | grandmother-ERG digging.stick see-NONPAST", "r149_present_grandmother_digging_stick", ["babi", "juwal", "nyaji-l"], "Common-noun A ERG; selected juwal implement sense."),
]


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("r149_"):
            issues.append(f"{label}: Rule 149 frame must start with r149_")
        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 149")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied action 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 149 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 149")
        if any(bad in english_low for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied action/use 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 149 draft: implements/materials lexical expansion after Rule 148", "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 149 source pass admitted ten implement/material heads: kalka, naybu, waymbil, karra, makarr, "
            "yinba, balur, kulji, juku, and juwal. Dictionary, Patz grammar, current lexeme DB, and corpus-surface "
            "readback completed; juwal is selected only as digging stick, and juku only as wood/material in this batch."
        ),
        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="lexical-scope",
        actor="claude-main",
        detail=(
            "Rule 149 is an implement/material lexical pass using state, support-location, bare perception, located "
            "perception, and present perception frames only. It excludes cutting, spearing, sharpening, hitting, "
            "catching, throwing, tying, making, scraping, poking, killing, fish-catch semantics, target case forms, "
            "instrument morphology, compounds, possessives, 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 cross-corpus duplicates.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_191.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 Rule 149 target per row, selected English senses enforced, no action/use field, no instruments, no target case forms, approved support locatives only, common-noun A ERG, and pronoun A bare.",
        command="python3 batch_scripts/bank_191.py static scan",
        artifact_path="batch_scripts/bank_191.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 149 implement/material lexical-expansion rows.",
        command="python3 batch_scripts/bank_191.py",
        artifact_path="batch_scripts/bank_191.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())
