#!/usr/bin/env python3
"""Bank batch-198: Rule 156 construction consolidation after Rule 155."""

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

TARGET_HEADS = {
    "kabal": "Leichhardt.tree",
    "jujabala": "ironwood.tree",
    "kangka": "wild.grape",
    "nganjirr": "grass.tree",
    "junda": "wild.plum",
    "jikan": "grass",
    "buyku": "paperbark",
    "kanunjul": "grass.tree.resin",
    "yibuy": "loya.cane",
    "wukay": "hairy.yam",
}
TARGET_ENGLISH = {
    "kabal": "leichhardt tree",
    "jujabala": "ironwood tree",
    "kangka": "wild grape",
    "nganjirr": "grass tree",
    "junda": "wild plum",
    "jikan": "grass",
    "buyku": "paperbark",
    "kanunjul": "grass-tree resin",
    "yibuy": "loya cane",
    "wukay": "hairy yam",
}
PRONOUN_A = {"ngayu", "yundu", "ngana", "jana"}
COMMON_A = {"ngamu-ngku", "nganjan-angka", "karrkay-ngku", "babi-ngka", "kami-ngka", "jalbu-ngku", "dingkar-angka"}
DENY_KUKU = {
    "baka", "bakan", "nuka", "nukan", "bangka", "bangkan", "waju", "wajun", "yurri", "yurrin", "nyanda",
    "nyandan", "wukurri", "wukurril", "kaja", "kajan", "dinda", "dindan", "wayju", "wayjun", "mani", "manin",
    "wundi", "wundin", "bunga", "bungan", "mumba", "mumban", "yijarri", "yijarrin", "daka", "dakan",
    "dunga", "dungan", "kada", "kadan", "kaday", "jarramali", "kaba", "muyar", "wungariji",
}
DENY_ENGLISH = (
    "dig", "dug", "eat", "ate", "eating", "gather", "burn", "burning", "scrape", "chop", "weave", "tie",
    "cook", "medicine", "remedy", "bark use", "resin use", "storm", "thunder", "rain", "wind", "season",
    "fruit", "food", "yam food", "material", "walking stick", "roof", "cover", "carry",
)


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 Leichhardt tree is here.", "Kabal yaluy.", "kabal yaluy | Leichhardt.tree here", "r156_deictic_leichhardt_tree_here", ["kabal", "yaluy"], "Rule 156 retained target; yaluy local demonstrative here."),
    row(2, "The ironwood tree is here.", "Jujabala yaluy.", "jujabala yaluy | ironwood.tree here", "r156_deictic_ironwood_tree_here", ["jujabala", "yaluy"], "Retained ironwood-tree target; no burning-use row."),
    row(3, "The wild grape is here.", "Kangka yaluy.", "kangka yaluy | wild.grape here", "r156_deictic_wild_grape_here", ["kangka", "yaluy"], "Retained wild-grape target; no medicine or storm-control row."),
    row(4, "The grass tree is here.", "Nganjirr yaluy.", "nganjirr yaluy | grass.tree here", "r156_deictic_grass_tree_here", ["nganjirr", "yaluy"], "Retained grass-tree target; no burning/ritual row."),
    row(5, "The wild plum is here.", "Junda yaluy.", "junda yaluy | wild.plum here", "r156_deictic_wild_plum_here", ["junda", "yaluy"], "Retained wild-plum target; no eating/gathering row."),
    row(6, "The grass is here.", "Jikan yaluy.", "jikan yaluy | grass here", "r156_deictic_grass_here", ["jikan", "yaluy"], "Retained grass target; no walking-through/snake/feed row."),
    row(7, "The paperbark is here.", "Buyku yaluy.", "buyku yaluy | paperbark here", "r156_deictic_paperbark_here", ["buyku", "yaluy"], "Retained paperbark target; no cover/roof/material row."),
    row(8, "The grass-tree resin is here.", "Kanunjul yaluy.", "kanunjul yaluy | grass.tree.resin here", "r156_deictic_resin_here", ["kanunjul", "yaluy"], "Retained grass-tree resin target; no burning/storm-control row."),
    row(9, "The loya cane is here.", "Yibuy yaluy.", "yibuy yaluy | loya.cane here", "r156_deictic_loya_cane_here", ["yibuy", "yaluy"], "Retained loya-cane target; no weaving/tying/material row."),
    row(10, "The hairy yam is here.", "Wukay yaluy.", "wukay yaluy | hairy.yam here", "r156_deictic_hairy_yam_here", ["wukay", "yaluy"], "Retained hairy-yam target; no digging/eating/cooking row."),
    row(11, "I see the Leichhardt tree.", "Ngayu kabal nyajil.", "ngayu kabal nyaji-l | I Leichhardt.tree see-NONPAST", "r156_present_i_leichhardt_tree", ["ngayu", "kabal", "nyaji-l"], "Pronoun A bare; retained target bare; nyaji-l nonpast."),
    row(12, "You see the ironwood tree.", "Yundu jujabala nyajil.", "yundu jujabala nyaji-l | you ironwood.tree see-NONPAST", "r156_present_you_ironwood_tree", ["yundu", "jujabala", "nyaji-l"], "Second-person pronoun A bare; retained target bare."),
    row(13, "I see the wild grape.", "Ngayu kangka nyajil.", "ngayu kangka nyaji-l | I wild.grape see-NONPAST", "r156_present_i_wild_grape", ["ngayu", "kangka", "nyaji-l"], "Pronoun A bare; wild-grape noun only."),
    row(14, "You see the grass tree.", "Yundu nganjirr nyajil.", "yundu nganjirr nyaji-l | you grass.tree see-NONPAST", "r156_present_you_grass_tree", ["yundu", "nganjirr", "nyaji-l"], "Second-person pronoun A bare; grass-tree noun only."),
    row(15, "I see the wild plum.", "Ngayu junda nyajil.", "ngayu junda nyaji-l | I wild.plum see-NONPAST", "r156_present_i_wild_plum", ["ngayu", "junda", "nyaji-l"], "Pronoun A bare; wild-plum noun only."),
    row(16, "You see the grass.", "Yundu jikan nyajil.", "yundu jikan nyaji-l | you grass see-NONPAST", "r156_present_you_grass", ["yundu", "jikan", "nyaji-l"], "Second-person pronoun A bare; grass noun only."),
    row(17, "I see the paperbark.", "Ngayu buyku nyajil.", "ngayu buyku nyaji-l | I paperbark see-NONPAST", "r156_present_i_paperbark", ["ngayu", "buyku", "nyaji-l"], "Pronoun A bare; paperbark noun only."),
    row(18, "You see the grass-tree resin.", "Yundu kanunjul nyajil.", "yundu kanunjul nyaji-l | you grass.tree.resin see-NONPAST", "r156_present_you_resin", ["yundu", "kanunjul", "nyaji-l"], "Second-person pronoun A bare; resin noun only."),
    row(19, "I see the loya cane.", "Ngayu yibuy nyajil.", "ngayu yibuy nyaji-l | I loya.cane see-NONPAST", "r156_present_i_loya_cane", ["ngayu", "yibuy", "nyaji-l"], "Pronoun A bare; loya-cane noun only."),
    row(20, "You see the hairy yam.", "Yundu wukay nyajil.", "yundu wukay nyaji-l | you hairy.yam see-NONPAST", "r156_present_you_hairy_yam", ["yundu", "wukay", "nyaji-l"], "Second-person pronoun A bare; hairy-yam noun only."),
    row(21, "We see the Leichhardt tree.", "Ngana kabal nyajil.", "ngana kabal nyaji-l | we Leichhardt.tree see-NONPAST", "r156_present_we_leichhardt_tree", ["ngana", "kabal", "nyaji-l"], "Inclusive pronoun A bare; retained target bare."),
    row(22, "They see the ironwood tree.", "Jana jujabala nyajil.", "jana jujabala nyaji-l | they ironwood.tree see-NONPAST", "r156_present_they_ironwood_tree", ["jana", "jujabala", "nyaji-l"], "Third-person plural pronoun A bare; retained target bare."),
    row(23, "Mother sees the wild grape.", "Ngamu-ngku kangka nyajil.", "ngamu-ngku kangka nyaji-l | mother-ERG wild.grape see-NONPAST", "r156_present_mother_wild_grape", ["ngamu", "kangka", "nyaji-l"], "Common-noun A ERG; wild-grape noun only."),
    row(24, "Father sees the grass tree.", "Nganjan-angka nganjirr nyajil.", "nganjan-angka nganjirr nyaji-l | father-ERG grass.tree see-NONPAST", "r156_present_father_grass_tree", ["nganjan", "nganjirr", "nyaji-l"], "Common-noun A ERG; grass-tree noun only."),
    row(25, "The child sees the wild plum.", "Karrkay-ngku junda nyajil.", "karrkay-ngku junda nyaji-l | child-ERG wild.plum see-NONPAST", "r156_present_child_wild_plum", ["karrkay", "junda", "nyaji-l"], "Common-noun A ERG; wild-plum noun only."),
    row(26, "Grandmother sees the grass.", "Babi-ngka jikan nyajil.", "babi-ngka jikan nyaji-l | grandmother-ERG grass see-NONPAST", "r156_present_grandmother_grass", ["babi", "jikan", "nyaji-l"], "Common-noun A ERG; grass noun only."),
    row(27, "Grandfather sees the paperbark.", "Kami-ngka buyku nyajil.", "kami-ngka buyku nyaji-l | grandfather-ERG paperbark see-NONPAST", "r156_present_grandfather_paperbark", ["kami", "buyku", "nyaji-l"], "Common-noun A ERG; paperbark noun only."),
    row(28, "The woman sees the grass-tree resin.", "Jalbu-ngku kanunjul nyajil.", "jalbu-ngku kanunjul nyaji-l | woman-ERG grass.tree.resin see-NONPAST", "r156_present_woman_resin", ["jalbu", "kanunjul", "nyaji-l"], "Common-noun A ERG; resin noun only."),
    row(29, "The man sees the loya cane.", "Dingkar-angka yibuy nyajil.", "dingkar-angka yibuy nyaji-l | man-ERG loya.cane see-NONPAST", "r156_present_man_loya_cane", ["dingkar", "yibuy", "nyaji-l"], "Common-noun A ERG; loya-cane noun only."),
    row(30, "We see the hairy yam.", "Ngana wukay nyajil.", "ngana wukay nyaji-l | we hairy.yam see-NONPAST", "r156_present_we_hairy_yam", ["ngana", "wukay", "nyaji-l"], "Inclusive pronoun A bare; hairy-yam noun only."),
    row(31, "We saw the Leichhardt tree.", "Ngana kabal nyajin.", "ngana kabal nyaji-ny | we Leichhardt.tree see-PAST", "r156_past_we_leichhardt_tree", ["ngana", "kabal", "nyaji-l"], "Inclusive pronoun A bare; past perception."),
    row(32, "You saw the ironwood tree.", "Yundu jujabala nyajin.", "yundu jujabala nyaji-ny | you ironwood.tree see-PAST", "r156_past_you_ironwood_tree", ["yundu", "jujabala", "nyaji-l"], "Second-person pronoun A bare; past perception."),
    row(33, "They saw the wild grape.", "Jana kangka nyajin.", "jana kangka nyaji-ny | they wild.grape see-PAST", "r156_past_they_wild_grape", ["jana", "kangka", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(34, "Father saw the grass tree.", "Nganjan-angka nganjirr nyajin.", "nganjan-angka nganjirr nyaji-ny | father-ERG grass.tree see-PAST", "r156_past_father_grass_tree", ["nganjan", "nganjirr", "nyaji-l"], "Common-noun A ERG; past perception."),
    row(35, "The child saw the wild plum.", "Karrkay-ngku junda nyajin.", "karrkay-ngku junda nyaji-ny | child-ERG wild.plum see-PAST", "r156_past_child_wild_plum", ["karrkay", "junda", "nyaji-l"], "Common-noun A ERG; wild-plum noun only."),
    row(36, "Grandmother saw the grass.", "Babi-ngka jikan nyajin.", "babi-ngka jikan nyaji-ny | grandmother-ERG grass see-PAST", "r156_past_grandmother_grass", ["babi", "jikan", "nyaji-l"], "Common-noun A ERG; grass noun only."),
    row(37, "Grandfather saw the paperbark.", "Kami-ngka buyku nyajin.", "kami-ngka buyku nyaji-ny | grandfather-ERG paperbark see-PAST", "r156_past_grandfather_paperbark", ["kami", "buyku", "nyaji-l"], "Common-noun A ERG; paperbark noun only."),
    row(38, "The woman saw the grass-tree resin.", "Jalbu-ngku kanunjul nyajin.", "jalbu-ngku kanunjul nyaji-ny | woman-ERG grass.tree.resin see-PAST", "r156_past_woman_resin", ["jalbu", "kanunjul", "nyaji-l"], "Common-noun A ERG; resin noun only."),
    row(39, "The man saw the loya cane.", "Dingkar-angka yibuy nyajin.", "dingkar-angka yibuy nyaji-ny | man-ERG loya.cane see-PAST", "r156_past_man_loya_cane", ["dingkar", "yibuy", "nyaji-l"], "Common-noun A ERG; loya-cane noun only."),
    row(40, "We saw the hairy yam.", "Ngana wukay nyajin.", "ngana wukay nyaji-ny | we hairy.yam see-PAST", "r156_past_we_hairy_yam", ["ngana", "wukay", "nyaji-l"], "Inclusive pronoun A bare; hairy-yam noun only."),
    row(41, "I see the Leichhardt tree there.", "Ngayu kabal yinyay nyajil.", "ngayu kabal yinyay nyaji-l | I Leichhardt.tree there see-NONPAST", "r156_present_i_leichhardt_tree_there", ["ngayu", "kabal", "yinyay", "nyaji-l"], "Pronoun A bare; yinyay support; retained target bare."),
    row(42, "We see the ironwood tree there.", "Ngana jujabala yinyay nyajil.", "ngana jujabala yinyay nyaji-l | we ironwood.tree there see-NONPAST", "r156_present_we_ironwood_tree_there", ["ngana", "jujabala", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support."),
    row(43, "They see the wild grape there.", "Jana kangka yinyay nyajil.", "jana kangka yinyay nyaji-l | they wild.grape there see-NONPAST", "r156_present_they_wild_grape_there", ["jana", "kangka", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; yinyay support."),
    row(44, "Mother sees the grass tree there.", "Ngamu-ngku nganjirr yinyay nyajil.", "ngamu-ngku nganjirr yinyay nyaji-l | mother-ERG grass.tree there see-NONPAST", "r156_present_mother_grass_tree_there", ["ngamu", "nganjirr", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(45, "Father sees the wild plum there.", "Nganjan-angka junda yinyay nyajil.", "nganjan-angka junda yinyay nyaji-l | father-ERG wild.plum there see-NONPAST", "r156_present_father_wild_plum_there", ["nganjan", "junda", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(46, "The child sees the grass there.", "Karrkay-ngku jikan yinyay nyajil.", "karrkay-ngku jikan yinyay nyaji-l | child-ERG grass there see-NONPAST", "r156_present_child_grass_there", ["karrkay", "jikan", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(47, "Grandmother sees the paperbark there.", "Babi-ngka buyku yinyay nyajil.", "babi-ngka buyku yinyay nyaji-l | grandmother-ERG paperbark there see-NONPAST", "r156_present_grandmother_paperbark_there", ["babi", "buyku", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(48, "Grandfather sees the grass-tree resin there.", "Kami-ngka kanunjul yinyay nyajil.", "kami-ngka kanunjul yinyay nyaji-l | grandfather-ERG grass.tree.resin there see-NONPAST", "r156_present_grandfather_resin_there", ["kami", "kanunjul", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(49, "The woman sees the loya cane there.", "Jalbu-ngku yibuy yinyay nyajil.", "jalbu-ngku yibuy yinyay nyaji-l | woman-ERG loya.cane there see-NONPAST", "r156_present_woman_loya_cane_there", ["jalbu", "yibuy", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
    row(50, "The man sees the hairy yam there.", "Dingkar-angka wukay yinyay nyajil.", "dingkar-angka wukay yinyay nyaji-l | man-ERG hairy.yam there see-NONPAST", "r156_present_man_hairy_yam_there", ["dingkar", "wukay", "yinyay", "nyaji-l"], "Common-noun A ERG; yinyay support."),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", low) is not None


def first_word(low: str) -> str:
    return low.split()[0].strip(".,!?;:\"")


def has_target_case(low: str, head: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:ngka|ngku|angka|nga|ngu|ba|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu|iji)\b", low) is not None


def english_has_denied(english_low: str, denied: str) -> bool:
    if " " in denied:
        return denied in english_low
    return re.search(rf"\b{re.escape(denied)}\b", english_low) is not None


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"{LABEL}: expected 50 rows, found {len(ROWS)}")
    seen_ku: set[str] = set()
    for expected, row_data in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row_data
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        is_deictic = seq <= 10
        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("r156_"):
            issues.append(f"{label}: Rule 156 frame must start with r156_")
        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 156")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied plant-use/weather 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 retained Rule 155 target head, found {targets}")
        for head in targets:
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if TARGET_HEADS[head] not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {TARGET_HEADS[head]}")
            if TARGET_ENGLISH[head] not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {TARGET_ENGLISH[head]!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if is_deictic:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: bare deictic rows must not use nyaji-l")
            if not has_token(low, "yaluy") or "yaluy" not in words:
                issues.append(f"{label}: Rule 156 deictic rows require yaluy")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 156 perception rows must use nyaji-l")
            if has_token(low, "yinyay") and "yinyay" not in words:
                issues.append(f"{label}: yinyay support missing from words_used")
            if has_token(low, "yaluy") and "yaluy" not in words:
                issues.append(f"{label}: yaluy support missing from words_used")
            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 first in COMMON_A and not ("-ngku" in first or "-ngka" in first or "-angka" in first):
                issues.append(f"{label}: common-noun A must be ERG-marked")
            if "nyajin" in low and "see-PAST" not in analysis:
                issues.append(f"{label}: nyajin must be glossed as see-PAST")
            if "nyajil" in low and "see-NONPAST" not in analysis:
                issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied plant-use/weather field in English")
        if not evidence or not confidence:
            issues.append(f"{label}: missing evidence/confidence")
    return issues


def main() -> int:
    issues = scan_static()
    if issues:
        print("pre-bank scan failed:")
        for issue in issues:
            print(f"  - {issue}")
        return 1

    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    existing = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()
    if existing:
        batch_id = existing[0]
        accepted = db.execute(
            "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status IN ('accepted','revised')",
            (batch_id,),
        ).fetchone()[0]
        if accepted:
            raise SystemExit(f"{LABEL} already has accepted/revised rows; refusing to overwrite")
        db.execute("DELETE FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)", (batch_id,))
        db.execute("DELETE FROM sentences WHERE batch_id=?", (batch_id,))
        db.execute("UPDATE batches SET notes=?, created_at=? WHERE id=?", ("rebanked under_review", NOW, batch_id))
    else:
        cur = db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 156 draft: construction consolidation after Rule 155", "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 156 source pass retained Rule 155 plant-resource targets and admitted no new plant heads. "
            "Dictionary, Patz grammar, lexeme-table, and corpus-surface readback confirmed target senses, yaluy/yinyay "
            "deictics, nyaji-l perception, bare pronoun A forms, and ERG-marked common-noun A forms."
        ),
        command="dictionary.yaml readback; grammar.md pronoun/deictic/nyaji and nominal case readback; sqlite lexeme and surface 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 156 is a construction consolidation pass: yaluy deictic identification, bare present/past perception, "
            "and yinyay-supported present perception. It excludes new target heads, plant-use predicates, medicine, "
            "food-use, material-source, burning/storm-control, target case forms, and target compounds."
        ),
        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_198.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 plant-resource target per row, selected English senses enforced, no target case or compound morphology, no plant-use predicates, no medicine/burning/material-source/food-use import, common-noun A ERG, and pronoun A bare.",
                 command="python3 batch_scripts/bank_198.py static scan", artifact_path="batch_scripts/bank_198.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 156 construction-consolidation rows.",
                 command="python3 batch_scripts/bank_198.py", artifact_path="batch_scripts/bank_198.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())
