#!/usr/bin/env python3
"""Bank batch-197: Rule 155 plant-resource lexical expansion after Rule 154."""

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-197"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-197-plant-resource-lexical-expansion-after-rule154-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": "resin",
    "yibuy": "loya cane",
    "wukay": "hairy yam",
}
PRONOUN_A = {"ngayu", "yundu", "jana"}
COMMON_A = {"ngamu-ngku"}
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",
)


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 there.", "Kabal yinyay.", "kabal yinyay | Leichhardt.tree there", "r155_deictic_leichhardt_tree_there", ["kabal", "yinyay"], "Dictionary/Patz kabal Leichhardt tree; yinyay local demonstrative."),
    row(2, "The ironwood tree is there.", "Jujabala yinyay.", "jujabala yinyay | ironwood.tree there", "r155_deictic_ironwood_tree_there", ["jujabala", "yinyay"], "Dictionary/Patz jujabala ironwood tree; no burning-use row."),
    row(3, "The wild grape is there.", "Kangka yinyay.", "kangka yinyay | wild.grape there", "r155_deictic_wild_grape_there", ["kangka", "yinyay"], "Dictionary kangka wild grape; target bare."),
    row(4, "The grass tree is there.", "Nganjirr yinyay.", "nganjirr yinyay | grass.tree there", "r155_deictic_grass_tree_there", ["nganjirr", "yinyay"], "Dictionary/Patz nganjirr grass tree; no burning-use row."),
    row(5, "The wild plum is there.", "Junda yinyay.", "junda yinyay | wild.plum there", "r155_deictic_wild_plum_there", ["junda", "yinyay"], "Dictionary junda wild plum; no eating/gathering row."),
    row(6, "The grass is there.", "Jikan yinyay.", "jikan yinyay | grass there", "r155_deictic_grass_there", ["jikan", "yinyay"], "Dictionary/Patz jikan grass; target bare."),
    row(7, "The paperbark is there.", "Buyku yinyay.", "buyku yinyay | paperbark there", "r155_deictic_paperbark_there", ["buyku", "yinyay"], "Dictionary/Patz buyku paperbark; no material-use row."),
    row(8, "The grass-tree resin is there.", "Kanunjul yinyay.", "kanunjul yinyay | grass.tree.resin there", "r155_deictic_resin_there", ["kanunjul", "yinyay"], "Dictionary kanunjul grass-tree resin; no burning-use row."),
    row(9, "The loya cane is there.", "Yibuy yinyay.", "yibuy yinyay | loya.cane there", "r155_deictic_loya_cane_there", ["yibuy", "yinyay"], "Dictionary/Patz yibuy loya cane; no weaving/tie row."),
    row(10, "The hairy yam is there.", "Wukay yinyay.", "wukay yinyay | hairy.yam there", "r155_deictic_hairy_yam_there", ["wukay", "yinyay"], "Dictionary/Patz wukay hairy yam; no digging/eating row."),
    row(11, "I see the Leichhardt tree here.", "Ngayu kabal yaluy nyajil.", "ngayu kabal yaluy nyaji-l | I Leichhardt.tree here see-NONPAST", "r155_present_i_leichhardt_tree_here", ["ngayu", "kabal", "yaluy", "nyaji-l"], "Pronoun A bare; target bare; yaluy support."),
    row(12, "I see the ironwood tree here.", "Ngayu jujabala yaluy nyajil.", "ngayu jujabala yaluy nyaji-l | I ironwood.tree here see-NONPAST", "r155_present_i_ironwood_tree_here", ["ngayu", "jujabala", "yaluy", "nyaji-l"], "Pronoun A bare; ironwood tree target."),
    row(13, "I see the wild grape here.", "Ngayu kangka yaluy nyajil.", "ngayu kangka yaluy nyaji-l | I wild.grape here see-NONPAST", "r155_present_i_wild_grape_here", ["ngayu", "kangka", "yaluy", "nyaji-l"], "Pronoun A bare; wild grape target."),
    row(14, "I see the grass tree here.", "Ngayu nganjirr yaluy nyajil.", "ngayu nganjirr yaluy nyaji-l | I grass.tree here see-NONPAST", "r155_present_i_grass_tree_here", ["ngayu", "nganjirr", "yaluy", "nyaji-l"], "Pronoun A bare; grass tree target."),
    row(15, "I see the wild plum here.", "Ngayu junda yaluy nyajil.", "ngayu junda yaluy nyaji-l | I wild.plum here see-NONPAST", "r155_present_i_wild_plum_here", ["ngayu", "junda", "yaluy", "nyaji-l"], "Pronoun A bare; wild plum target."),
    row(16, "I see the grass here.", "Ngayu jikan yaluy nyajil.", "ngayu jikan yaluy nyaji-l | I grass here see-NONPAST", "r155_present_i_grass_here", ["ngayu", "jikan", "yaluy", "nyaji-l"], "Pronoun A bare; grass target."),
    row(17, "I see the paperbark here.", "Ngayu buyku yaluy nyajil.", "ngayu buyku yaluy nyaji-l | I paperbark here see-NONPAST", "r155_present_i_paperbark_here", ["ngayu", "buyku", "yaluy", "nyaji-l"], "Pronoun A bare; paperbark target."),
    row(18, "I see the grass-tree resin here.", "Ngayu kanunjul yaluy nyajil.", "ngayu kanunjul yaluy nyaji-l | I grass.tree.resin here see-NONPAST", "r155_present_i_resin_here", ["ngayu", "kanunjul", "yaluy", "nyaji-l"], "Pronoun A bare; resin target."),
    row(19, "I see the loya cane here.", "Ngayu yibuy yaluy nyajil.", "ngayu yibuy yaluy nyaji-l | I loya.cane here see-NONPAST", "r155_present_i_loya_cane_here", ["ngayu", "yibuy", "yaluy", "nyaji-l"], "Pronoun A bare; loya cane target."),
    row(20, "I see the hairy yam here.", "Ngayu wukay yaluy nyajil.", "ngayu wukay yaluy nyaji-l | I hairy.yam here see-NONPAST", "r155_present_i_hairy_yam_here", ["ngayu", "wukay", "yaluy", "nyaji-l"], "Pronoun A bare; hairy yam target."),
    row(21, "You see the Leichhardt tree here.", "Yundu kabal yaluy nyajil.", "yundu kabal yaluy nyaji-l | you Leichhardt.tree here see-NONPAST", "r155_present_you_leichhardt_tree_here", ["yundu", "kabal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target bare."),
    row(22, "You see the ironwood tree here.", "Yundu jujabala yaluy nyajil.", "yundu jujabala yaluy nyaji-l | you ironwood.tree here see-NONPAST", "r155_present_you_ironwood_tree_here", ["yundu", "jujabala", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(23, "You see the wild grape here.", "Yundu kangka yaluy nyajil.", "yundu kangka yaluy nyaji-l | you wild.grape here see-NONPAST", "r155_present_you_wild_grape_here", ["yundu", "kangka", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(24, "You see the grass tree here.", "Yundu nganjirr yaluy nyajil.", "yundu nganjirr yaluy nyaji-l | you grass.tree here see-NONPAST", "r155_present_you_grass_tree_here", ["yundu", "nganjirr", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(25, "You see the wild plum here.", "Yundu junda yaluy nyajil.", "yundu junda yaluy nyaji-l | you wild.plum here see-NONPAST", "r155_present_you_wild_plum_here", ["yundu", "junda", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(26, "You see the grass here.", "Yundu jikan yaluy nyajil.", "yundu jikan yaluy nyaji-l | you grass here see-NONPAST", "r155_present_you_grass_here", ["yundu", "jikan", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(27, "You see the paperbark here.", "Yundu buyku yaluy nyajil.", "yundu buyku yaluy nyaji-l | you paperbark here see-NONPAST", "r155_present_you_paperbark_here", ["yundu", "buyku", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(28, "You see the grass-tree resin here.", "Yundu kanunjul yaluy nyajil.", "yundu kanunjul yaluy nyaji-l | you grass.tree.resin here see-NONPAST", "r155_present_you_resin_here", ["yundu", "kanunjul", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(29, "You see the loya cane here.", "Yundu yibuy yaluy nyajil.", "yundu yibuy yaluy nyaji-l | you loya.cane here see-NONPAST", "r155_present_you_loya_cane_here", ["yundu", "yibuy", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(30, "You see the hairy yam here.", "Yundu wukay yaluy nyajil.", "yundu wukay yaluy nyaji-l | you hairy.yam here see-NONPAST", "r155_present_you_hairy_yam_here", ["yundu", "wukay", "yaluy", "nyaji-l"], "Second-person pronoun A bare."),
    row(31, "They saw the Leichhardt tree here.", "Jana kabal yaluy nyajin.", "jana kabal yaluy nyaji-ny | they Leichhardt.tree here see-PAST", "r155_past_they_leichhardt_tree_here", ["jana", "kabal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the ironwood tree here.", "Jana jujabala yaluy nyajin.", "jana jujabala yaluy nyaji-ny | they ironwood.tree here see-PAST", "r155_past_they_ironwood_tree_here", ["jana", "jujabala", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(33, "They saw the wild grape here.", "Jana kangka yaluy nyajin.", "jana kangka yaluy nyaji-ny | they wild.grape here see-PAST", "r155_past_they_wild_grape_here", ["jana", "kangka", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(34, "They saw the grass tree here.", "Jana nganjirr yaluy nyajin.", "jana nganjirr yaluy nyaji-ny | they grass.tree here see-PAST", "r155_past_they_grass_tree_here", ["jana", "nganjirr", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(35, "They saw the wild plum here.", "Jana junda yaluy nyajin.", "jana junda yaluy nyaji-ny | they wild.plum here see-PAST", "r155_past_they_wild_plum_here", ["jana", "junda", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(36, "They saw the grass here.", "Jana jikan yaluy nyajin.", "jana jikan yaluy nyaji-ny | they grass here see-PAST", "r155_past_they_grass_here", ["jana", "jikan", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(37, "They saw the paperbark here.", "Jana buyku yaluy nyajin.", "jana buyku yaluy nyaji-ny | they paperbark here see-PAST", "r155_past_they_paperbark_here", ["jana", "buyku", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(38, "They saw the grass-tree resin here.", "Jana kanunjul yaluy nyajin.", "jana kanunjul yaluy nyaji-ny | they grass.tree.resin here see-PAST", "r155_past_they_resin_here", ["jana", "kanunjul", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(39, "They saw the loya cane here.", "Jana yibuy yaluy nyajin.", "jana yibuy yaluy nyaji-ny | they loya.cane here see-PAST", "r155_past_they_loya_cane_here", ["jana", "yibuy", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(40, "They saw the hairy yam here.", "Jana wukay yaluy nyajin.", "jana wukay yaluy nyaji-ny | they hairy.yam here see-PAST", "r155_past_they_hairy_yam_here", ["jana", "wukay", "yaluy", "nyaji-l"], "Past perception; target bare."),
    row(41, "Mother sees the Leichhardt tree here.", "Ngamu-ngku kabal yaluy nyajil.", "ngamu-ngku kabal yaluy nyaji-l | mother-ERG Leichhardt.tree here see-NONPAST", "r155_present_mother_leichhardt_tree_here", ["ngamu", "kabal", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(42, "Mother sees the ironwood tree here.", "Ngamu-ngku jujabala yaluy nyajil.", "ngamu-ngku jujabala yaluy nyaji-l | mother-ERG ironwood.tree here see-NONPAST", "r155_present_mother_ironwood_tree_here", ["ngamu", "jujabala", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(43, "Mother sees the wild grape here.", "Ngamu-ngku kangka yaluy nyajil.", "ngamu-ngku kangka yaluy nyaji-l | mother-ERG wild.grape here see-NONPAST", "r155_present_mother_wild_grape_here", ["ngamu", "kangka", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(44, "Mother sees the grass tree here.", "Ngamu-ngku nganjirr yaluy nyajil.", "ngamu-ngku nganjirr yaluy nyaji-l | mother-ERG grass.tree here see-NONPAST", "r155_present_mother_grass_tree_here", ["ngamu", "nganjirr", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(45, "Mother sees the wild plum here.", "Ngamu-ngku junda yaluy nyajil.", "ngamu-ngku junda yaluy nyaji-l | mother-ERG wild.plum here see-NONPAST", "r155_present_mother_wild_plum_here", ["ngamu", "junda", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(46, "Mother sees the grass here.", "Ngamu-ngku jikan yaluy nyajil.", "ngamu-ngku jikan yaluy nyaji-l | mother-ERG grass here see-NONPAST", "r155_present_mother_grass_here", ["ngamu", "jikan", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(47, "Mother sees the paperbark here.", "Ngamu-ngku buyku yaluy nyajil.", "ngamu-ngku buyku yaluy nyaji-l | mother-ERG paperbark here see-NONPAST", "r155_present_mother_paperbark_here", ["ngamu", "buyku", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(48, "Mother sees the grass-tree resin here.", "Ngamu-ngku kanunjul yaluy nyajil.", "ngamu-ngku kanunjul yaluy nyaji-l | mother-ERG grass.tree.resin here see-NONPAST", "r155_present_mother_resin_here", ["ngamu", "kanunjul", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(49, "Mother sees the loya cane here.", "Ngamu-ngku yibuy yaluy nyajil.", "ngamu-ngku yibuy yaluy nyaji-l | mother-ERG loya.cane here see-NONPAST", "r155_present_mother_loya_cane_here", ["ngamu", "yibuy", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
    row(50, "Mother sees the hairy yam here.", "Ngamu-ngku wukay yaluy nyajil.", "ngamu-ngku wukay yaluy nyaji-l | mother-ERG hairy.yam here see-NONPAST", "r155_present_mother_hairy_yam_here", ["ngamu", "wukay", "yaluy", "nyaji-l"], "Common-noun A ERG; target bare."),
]


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("r155_"):
            issues.append(f"{label}: Rule 155 frame must start with r155_")
        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 155")
        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 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}: deictic rows must not use nyaji-l")
            if not has_token(low, "yinyay"):
                issues.append(f"{label}: deictic rows require yinyay")
        else:
            if not has_token(low, "yaluy") or "yaluy" not in words:
                issues.append(f"{label}: Rule 155 perception rows require yaluy support")
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 155 perception rows must use nyaji-l")
            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 "-ngku" not 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 155 draft: plant-resource lexical expansion after Rule 154", "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 155 source pass admitted plant-resource targets 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, and wukay hairy yam. Dictionary, Patz grammar, lexeme-table, and "
            "corpus-surface readback completed."
        ),
        command="dictionary.yaml exact readback; grammar.md occurrence readback; sqlite lexeme and surface 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 155 is a lexical pass for bare plant-resource heads in deictic and perception frames. It excludes "
            "target case forms, plant-use predicates, medicine preparation, burning/storm-control claims, food-use "
            "claims, material-source claims, and carry-forward weather/geography/implement traps."
        ),
        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_197.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 bare 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_197.py static scan", artifact_path="batch_scripts/bank_197.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 155 plant-resource lexical-expansion rows.",
                 command="python3 batch_scripts/bank_197.py", artifact_path="batch_scripts/bank_197.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())
