#!/usr/bin/env python3
"""Bank batch-205: Rule 163 plant/tree reference lexical expansion."""

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-205"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-205-plant-tree-reference-lexical-expansion-after-rule162-process.md"

TARGET_HEADS = {
    "buyukal": "buyukal tree",
    "dalkan": "casuarina pine",
    "dari": "boxwood tree",
    "dibul": "cane",
    "dilbal": "hickory tree",
    "dili": "corkwood pine",
    "jabarr": "baldy gum tree",
    "jakari": "spiderlily",
    "jama": "jama tree",
    "jilbar": "corkwood tree",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "mayi", "nuka", "nukan", "waju", "wajun", "warrmba", "warrmban", "mani", "manin", "daji", "dajin",
    "dinda", "dindan", "duda", "dudan", "wukurri", "wukurrin", "ngara", "ngaran", "kuni", "kunin",
    "yaka", "yakan", "balka", "balkan", "kida", "kidan", "dunga", "dungan", "wandi", "wandin",
    "baya", "kubu", "kurrma", "medicine", "juku", "bark", "spear", "storm", "bayan", "bubu",
}
DENY_ENGLISH = (
    "eat", "eats", "ate", "eaten", "food", "fruit", "nut", "medicine", "heal", "healed", "sore",
    "bark", "burn", "burned", "burnt", "fire", "smoke", "storm", "spear", "woomera", "timber",
    "wood", "stick", "weave", "woven", "tie", "tied", "basket", "place", "camp", "beach", "fruit",
    "gather", "gathered", "harvest", "harvested", "dig", "dug", "cook", "cooked", "roast", "roasted",
)


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 buyukal tree is here.", "Buyukal yaluy.", "buyukal yaluy | buyukal.tree here", "r163_deictic_buyukal_here", ["buyukal", "yaluy"], "Rule 163 admits dictionary-attested buyukal as a tree with English name unknown; bare yaluy deictic frame."),
    row(2, "The casuarina pine is here.", "Dalkan yaluy.", "dalkan yaluy | casuarina.pine here", "r163_deictic_dalkan_here", ["dalkan", "yaluy"], "Rule 163 admits dalkan as tree growing along beaches; Patz has dalkan-ba 'casuarina pine'; target remains bare."),
    row(3, "The boxwood tree is here.", "Dari yaluy.", "dari yaluy | boxwood.tree here", "r163_deictic_dari_here", ["dari", "yaluy"], "Rule 163 admits dictionary-attested dari boxwood tree; bare yaluy deictic frame."),
    row(4, "The cane is here.", "Dibul yaluy.", "dibul yaluy | cane here", "r163_deictic_dibul_here", ["dibul", "yaluy"], "Rule 163 admits dictionary-attested dibul cane; no material-use claim."),
    row(5, "The hickory tree is here.", "Dilbal yaluy.", "dilbal yaluy | hickory.tree here", "r163_deictic_dilbal_here", ["dilbal", "yaluy"], "Rule 163 admits dictionary-attested dilbal hickory tree; bare yaluy deictic frame."),
    row(6, "The corkwood pine is here.", "Dili yaluy.", "dili yaluy | corkwood.pine here", "r163_deictic_dili_here", ["dili", "yaluy"], "Rule 163 admits dili corkwood pine; Patz case table confirms bare dili and dili-mba."),
    row(7, "The baldy gum tree is here.", "Jabarr yaluy.", "jabarr yaluy | baldy.gum.tree here", "r163_deictic_jabarr_here", ["jabarr", "yaluy"], "Rule 163 admits dictionary-attested jabarr baldy gum tree; bare yaluy deictic frame."),
    row(8, "The spiderlily is here.", "Jakari yaluy.", "jakari yaluy | spiderlily here", "r163_deictic_jakari_here", ["jakari", "yaluy"], "Rule 163 admits dictionary-attested jakari spiderlily; no medicine or use claim."),
    row(9, "The jama tree is here.", "Jama yaluy.", "jama yaluy | jama.tree here", "r163_deictic_jama_here", ["jama", "yaluy"], "Rule 163 admits dictionary-attested jama as a tree type; bare yaluy deictic frame."),
    row(10, "The corkwood tree is here.", "Jilbar yaluy.", "jilbar yaluy | corkwood.tree here", "r163_deictic_jilbar_here", ["jilbar", "yaluy"], "Rule 163 admits dictionary-attested jilbar corkwood tree; bare yaluy deictic frame."),
    row(11, "I see the buyukal tree.", "Ngayu buyukal nyajil.", "ngayu buyukal nyaji-l | I buyukal.tree see-NONPAST", "r163_present_i_buyukal", ["ngayu", "buyukal", "nyaji-l"], "Pronoun A bare; target tree object bare."),
    row(12, "I see the casuarina pine.", "Ngayu dalkan nyajil.", "ngayu dalkan nyaji-l | I casuarina.pine see-NONPAST", "r163_present_i_dalkan", ["ngayu", "dalkan", "nyaji-l"], "Pronoun A bare; dalkan object bare, no locative."),
    row(13, "I see the boxwood tree.", "Ngayu dari nyajil.", "ngayu dari nyaji-l | I boxwood.tree see-NONPAST", "r163_present_i_dari", ["ngayu", "dari", "nyaji-l"], "Pronoun A bare; dari object bare."),
    row(14, "I see the cane.", "Ngayu dibul nyajil.", "ngayu dibul nyaji-l | I cane see-NONPAST", "r163_present_i_dibul", ["ngayu", "dibul", "nyaji-l"], "Pronoun A bare; dibul object bare."),
    row(15, "I see the hickory tree.", "Ngayu dilbal nyajil.", "ngayu dilbal nyaji-l | I hickory.tree see-NONPAST", "r163_present_i_dilbal", ["ngayu", "dilbal", "nyaji-l"], "Pronoun A bare; dilbal object bare."),
    row(16, "I see the corkwood pine.", "Ngayu dili nyajil.", "ngayu dili nyaji-l | I corkwood.pine see-NONPAST", "r163_present_i_dili", ["ngayu", "dili", "nyaji-l"], "Pronoun A bare; dili object bare, no dili-mba locative."),
    row(17, "I see the baldy gum tree.", "Ngayu jabarr nyajil.", "ngayu jabarr nyaji-l | I baldy.gum.tree see-NONPAST", "r163_present_i_jabarr", ["ngayu", "jabarr", "nyaji-l"], "Pronoun A bare; jabarr object bare."),
    row(18, "I see the spiderlily.", "Ngayu jakari nyajil.", "ngayu jakari nyaji-l | I spiderlily see-NONPAST", "r163_present_i_jakari", ["ngayu", "jakari", "nyaji-l"], "Pronoun A bare; jakari object bare."),
    row(19, "I see the jama tree.", "Ngayu jama nyajil.", "ngayu jama nyaji-l | I jama.tree see-NONPAST", "r163_present_i_jama", ["ngayu", "jama", "nyaji-l"], "Pronoun A bare; jama object bare."),
    row(20, "I see the corkwood tree.", "Ngayu jilbar nyajil.", "ngayu jilbar nyaji-l | I corkwood.tree see-NONPAST", "r163_present_i_jilbar", ["ngayu", "jilbar", "nyaji-l"], "Pronoun A bare; jilbar object bare."),
    row(21, "You see the buyukal tree there.", "Yundu buyukal yinyay nyajil.", "yundu buyukal yinyay nyaji-l | you buyukal.tree there see-NONPAST", "r163_present_you_buyukal_there", ["yundu", "buyukal", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(22, "You see the casuarina pine there.", "Yundu dalkan yinyay nyajil.", "yundu dalkan yinyay nyaji-l | you casuarina.pine there see-NONPAST", "r163_present_you_dalkan_there", ["yundu", "dalkan", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no target locative."),
    row(23, "You see the boxwood tree there.", "Yundu dari yinyay nyajil.", "yundu dari yinyay nyaji-l | you boxwood.tree there see-NONPAST", "r163_present_you_dari_there", ["yundu", "dari", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(24, "You see the cane there.", "Yundu dibul yinyay nyajil.", "yundu dibul yinyay nyaji-l | you cane there see-NONPAST", "r163_present_you_dibul_there", ["yundu", "dibul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no cane-use claim."),
    row(25, "You see the hickory tree there.", "Yundu dilbal yinyay nyajil.", "yundu dilbal yinyay nyaji-l | you hickory.tree there see-NONPAST", "r163_present_you_dilbal_there", ["yundu", "dilbal", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the corkwood pine there.", "Yundu dili yinyay nyajil.", "yundu dili yinyay nyaji-l | you corkwood.pine there see-NONPAST", "r163_present_you_dili_there", ["yundu", "dili", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no dili-mba target form."),
    row(27, "You see the baldy gum tree there.", "Yundu jabarr yinyay nyajil.", "yundu jabarr yinyay nyaji-l | you baldy.gum.tree there see-NONPAST", "r163_present_you_jabarr_there", ["yundu", "jabarr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the spiderlily there.", "Yundu jakari yinyay nyajil.", "yundu jakari yinyay nyaji-l | you spiderlily there see-NONPAST", "r163_present_you_jakari_there", ["yundu", "jakari", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no plant-use claim."),
    row(29, "You see the jama tree there.", "Yundu jama yinyay nyajil.", "yundu jama yinyay nyaji-l | you jama.tree there see-NONPAST", "r163_present_you_jama_there", ["yundu", "jama", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the corkwood tree there.", "Yundu jilbar yinyay nyajil.", "yundu jilbar yinyay nyaji-l | you corkwood.tree there see-NONPAST", "r163_present_you_jilbar_there", ["yundu", "jilbar", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the buyukal tree there.", "Jana buyukal yinyay nyajin.", "jana buyukal yinyay nyaji-ny | they buyukal.tree there see-PAST", "r163_past_they_buyukal_there", ["jana", "buyukal", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the casuarina pine there.", "Jana dalkan yinyay nyajin.", "jana dalkan yinyay nyaji-ny | they casuarina.pine there see-PAST", "r163_past_they_dalkan_there", ["jana", "dalkan", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(33, "They saw the boxwood tree there.", "Jana dari yinyay nyajin.", "jana dari yinyay nyaji-ny | they boxwood.tree there see-PAST", "r163_past_they_dari_there", ["jana", "dari", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(34, "They saw the cane there.", "Jana dibul yinyay nyajin.", "jana dibul yinyay nyaji-ny | they cane there see-PAST", "r163_past_they_dibul_there", ["jana", "dibul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(35, "They saw the hickory tree there.", "Jana dilbal yinyay nyajin.", "jana dilbal yinyay nyaji-ny | they hickory.tree there see-PAST", "r163_past_they_dilbal_there", ["jana", "dilbal", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(36, "They saw the corkwood pine there.", "Jana dili yinyay nyajin.", "jana dili yinyay nyaji-ny | they corkwood.pine there see-PAST", "r163_past_they_dili_there", ["jana", "dili", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(37, "They saw the baldy gum tree there.", "Jana jabarr yinyay nyajin.", "jana jabarr yinyay nyaji-ny | they baldy.gum.tree there see-PAST", "r163_past_they_jabarr_there", ["jana", "jabarr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(38, "They saw the spiderlily there.", "Jana jakari yinyay nyajin.", "jana jakari yinyay nyaji-ny | they spiderlily there see-PAST", "r163_past_they_jakari_there", ["jana", "jakari", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(39, "They saw the jama tree there.", "Jana jama yinyay nyajin.", "jana jama yinyay nyaji-ny | they jama.tree there see-PAST", "r163_past_they_jama_there", ["jana", "jama", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(40, "They saw the corkwood tree there.", "Jana jilbar yinyay nyajin.", "jana jilbar yinyay nyaji-ny | they corkwood.tree there see-PAST", "r163_past_they_jilbar_there", ["jana", "jilbar", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(41, "We see the buyukal tree here.", "Ngana buyukal yaluy nyajil.", "ngana buyukal yaluy nyaji-l | we buyukal.tree here see-NONPAST", "r163_present_we_buyukal_here", ["ngana", "buyukal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(42, "We see the casuarina pine here.", "Ngana dalkan yaluy nyajil.", "ngana dalkan yaluy nyaji-l | we casuarina.pine here see-NONPAST", "r163_present_we_dalkan_here", ["ngana", "dalkan", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(43, "We see the boxwood tree here.", "Ngana dari yaluy nyajil.", "ngana dari yaluy nyaji-l | we boxwood.tree here see-NONPAST", "r163_present_we_dari_here", ["ngana", "dari", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(44, "We see the cane here.", "Ngana dibul yaluy nyajil.", "ngana dibul yaluy nyaji-l | we cane here see-NONPAST", "r163_present_we_dibul_here", ["ngana", "dibul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no cane-use claim."),
    row(45, "We see the hickory tree here.", "Ngana dilbal yaluy nyajil.", "ngana dilbal yaluy nyaji-l | we hickory.tree here see-NONPAST", "r163_present_we_dilbal_here", ["ngana", "dilbal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(46, "We see the corkwood pine here.", "Ngana dili yaluy nyajil.", "ngana dili yaluy nyaji-l | we corkwood.pine here see-NONPAST", "r163_present_we_dili_here", ["ngana", "dili", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no target locative."),
    row(47, "We see the baldy gum tree here.", "Ngana jabarr yaluy nyajil.", "ngana jabarr yaluy nyaji-l | we baldy.gum.tree here see-NONPAST", "r163_present_we_jabarr_here", ["ngana", "jabarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(48, "We see the spiderlily here.", "Ngana jakari yaluy nyajil.", "ngana jakari yaluy nyaji-l | we spiderlily here see-NONPAST", "r163_present_we_jakari_here", ["ngana", "jakari", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no medicine or use claim."),
    row(49, "We see the jama tree here.", "Ngana jama yaluy nyajil.", "ngana jama yaluy nyaji-l | we jama.tree here see-NONPAST", "r163_present_we_jama_here", ["ngana", "jama", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(50, "We see the corkwood tree here.", "Ngana jilbar yaluy nyajil.", "ngana jilbar yaluy nyaji-l | we corkwood.tree here see-NONPAST", "r163_present_we_jilbar_here", ["ngana", "jilbar", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object 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|mba|mbu|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu|iji|nda|ndu|anda|undu|unji|nji|kari|baka)\b", low) is not None


def english_has_denied(english_low: str, denied: str) -> bool:
    return denied in english_low if " " in denied else 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)
        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("r163_"):
            issues.append(f"{label}: Rule 163 frame must start with r163_")
        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 loans are admitted in Rule 163")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied plant-use/event 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 163 target head, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected.replace(" ", ".") not in analysis and selected not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            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, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 163 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 163 perception rows must use nyaji-l")
            first = first_word(low)
            if first not in PRONOUN_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun")
            if 11 <= seq <= 20 and first != "ngayu":
                issues.append(f"{label}: rows 11-20 require ngayu")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            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/event/homograph 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 163 draft: plant/tree reference lexical expansion after Rule 162", "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 163 source pass selected plant/tree reference heads buyukal, dalkan, dari, dibul, dilbal, dili, jabarr, jakari, jama, and jilbar. Dictionary exact readback completed for all ten. Patz readback confirmed dalkan-ba and dili/dili-mba, support forms yaluy/yinyay, nyaji-l, and bare pronoun A forms; no conflicting Patz use found for dictionary-only heads.",
                 command="rg dictionary exact readback; rg grammar readback for target/support/pronoun forms; sqlite lexeme 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 163 is a lexical reference pass for ten plant/tree heads in bare yaluy deictic, bare perception, and deictic-supported perception frames. It excludes eating, fruit, medicine, bark use, burning, weaving, tying, spear-making, timber/material-source, storm-control, place-name, target case, target compounds, and ecological-event claims.",
                 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_205.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one target head per row; all targets bare; no loans; no plant-use/event tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_205.py static scan", artifact_path="batch_scripts/bank_205.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, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()

    under_review = db.execute(
        "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'",
        (batch_id,),
    ).fetchone()[0]
    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    print(f"banked {LABEL}: rows={len(ROWS)}, under_review={under_review}, verified_before_close={verified}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
