#!/usr/bin/env python3
"""Bank batch-209: Rule 167 flora reference lexical expansion after Rule 166."""

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

TARGET_HEADS = {
    "jina-jina": "water gum tree",
    "jarrangkal": "fig tree",
    "julbin": "scrub tree",
    "kunjarri": "palm",
    "kurruy": "plum tree",
    "malurri": "fern tree",
    "mawar": "vine",
    "maya": "vine",
    "wangay": "vine",
    "yawarr": "palm",
}
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",
    "buyku", "bijan", "dukal", "dakumbar", "jinjay", "jalnji", "ngakun", "ngunyin", "kaja", "kajal",
    "munja", "munjan", "jaba", "jaban", "kulba", "kulban", "wabu", "woomera",
}
DENY_ENGLISH = (
    "eat", "eats", "ate", "eaten", "edible", "food", "fruit", "nut", "medicine", "heal", "healed",
    "sore", "bark", "burn", "burned", "burnt", "fire", "smoke", "storm", "spear", "woomera", "timber",
    "wood", "stick", "weave", "woven", "tie", "tied", "string", "brace", "braces", "basket", "container",
    "cook", "cooked", "cooking", "roast", "roasted", "place", "camp", "main camp", "beach", "gather",
    "gathered", "harvest", "harvested", "dig", "dug", "pod", "pods", "seed", "seeds",
)


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 water gum tree is here.", "Jina-jina yaluy.", "jina-jina yaluy | water.gum.tree here", "r167_deictic_jinajina_here", ["jina-jina", "yaluy"], "Rule 167 admits dictionary-attested Yalanji jina-jina as water gum tree; no timber/woomera claim."),
    row(2, "The fig tree is here.", "Jarrangkal yaluy.", "jarrangkal yaluy | fig.tree here", "r167_deictic_jarrangkal_here", ["jarrangkal", "yaluy"], "Rule 167 admits jarrangkal as fig tree; no fruit/food row."),
    row(3, "The scrub tree is here.", "Julbin yaluy.", "julbin yaluy | scrub.tree here", "r167_deictic_julbin_here", ["julbin", "yaluy"], "Rule 167 admits julbin as scrub tree; edible-processing prose remains closed."),
    row(4, "The kunjarri palm is here.", "Kunjarri yaluy.", "kunjarri yaluy | palm here", "r167_deictic_kunjarri_here", ["kunjarri", "yaluy"], "Rule 167 admits kunjarri as palm; bark-container and edible-trunk prose remain closed."),
    row(5, "The plum tree is here.", "Kurruy yaluy.", "kurruy yaluy | plum.tree here", "r167_deictic_kurruy_here", ["kurruy", "yaluy"], "Rule 167 admits kurruy as plum tree; no fruit/food row."),
    row(6, "The fern tree is here.", "Malurri yaluy.", "malurri yaluy | fern.tree here", "r167_deictic_malurri_here", ["malurri", "yaluy"], "Rule 167 admits malurri as fern tree."),
    row(7, "The mawar vine is here.", "Mawar yaluy.", "mawar yaluy | vine here", "r167_deictic_mawar_here", ["mawar", "yaluy"], "Rule 167 admits mawar as vine; no braces/tying/string row."),
    row(8, "The maya vine is here.", "Maya yaluy.", "maya yaluy | vine here", "r167_deictic_maya_here", ["maya", "yaluy"], "Rule 167 admits maya as clinging plant/vine; reference only."),
    row(9, "The wangay vine is here.", "Wangay yaluy.", "wangay yaluy | vine here", "r167_deictic_wangay_here", ["wangay", "yaluy"], "Rule 167 admits wangay as vine; no fruit-bearing or Main Camp place row."),
    row(10, "The yawarr palm is here.", "Yawarr yaluy.", "yawarr yaluy | palm here", "r167_deictic_yawarr_here", ["yawarr", "yaluy"], "Rule 167 admits yawarr as palm; reference only."),
    row(11, "I see the water gum tree.", "Ngayu jina-jina nyajil.", "ngayu jina-jina nyaji-l | I water.gum.tree see-NONPAST", "r167_present_i_jinajina", ["ngayu", "jina-jina", "nyaji-l"], "Pronoun A bare; jina-jina object bare; no timber/woomera row."),
    row(12, "I see the fig tree.", "Ngayu jarrangkal nyajil.", "ngayu jarrangkal nyaji-l | I fig.tree see-NONPAST", "r167_present_i_jarrangkal", ["ngayu", "jarrangkal", "nyaji-l"], "Pronoun A bare; jarrangkal object bare; no fruit/food row."),
    row(13, "I see the scrub tree.", "Ngayu julbin nyajil.", "ngayu julbin nyaji-l | I scrub.tree see-NONPAST", "r167_present_i_julbin", ["ngayu", "julbin", "nyaji-l"], "Pronoun A bare; julbin object bare; no edible-processing row."),
    row(14, "I see the kunjarri palm.", "Ngayu kunjarri nyajil.", "ngayu kunjarri nyaji-l | I palm see-NONPAST", "r167_present_i_kunjarri", ["ngayu", "kunjarri", "nyaji-l"], "Pronoun A bare; kunjarri object bare; no bark/container/edible row."),
    row(15, "I see the plum tree.", "Ngayu kurruy nyajil.", "ngayu kurruy nyaji-l | I plum.tree see-NONPAST", "r167_present_i_kurruy", ["ngayu", "kurruy", "nyaji-l"], "Pronoun A bare; kurruy object bare; no fruit/food row."),
    row(16, "I see the fern tree.", "Ngayu malurri nyajil.", "ngayu malurri nyaji-l | I fern.tree see-NONPAST", "r167_present_i_malurri", ["ngayu", "malurri", "nyaji-l"], "Pronoun A bare; malurri object bare."),
    row(17, "I see the mawar vine.", "Ngayu mawar nyajil.", "ngayu mawar nyaji-l | I vine see-NONPAST", "r167_present_i_mawar", ["ngayu", "mawar", "nyaji-l"], "Pronoun A bare; mawar object bare; no tying/string row."),
    row(18, "I see the maya vine.", "Ngayu maya nyajil.", "ngayu maya nyaji-l | I vine see-NONPAST", "r167_present_i_maya", ["ngayu", "maya", "nyaji-l"], "Pronoun A bare; maya object bare."),
    row(19, "I see the wangay vine.", "Ngayu wangay nyajil.", "ngayu wangay nyaji-l | I vine see-NONPAST", "r167_present_i_wangay", ["ngayu", "wangay", "nyaji-l"], "Pronoun A bare; wangay object bare; no fruit/place row."),
    row(20, "I see the yawarr palm.", "Ngayu yawarr nyajil.", "ngayu yawarr nyaji-l | I palm see-NONPAST", "r167_present_i_yawarr", ["ngayu", "yawarr", "nyaji-l"], "Pronoun A bare; yawarr object bare."),
    row(21, "You see the water gum tree there.", "Yundu jina-jina yinyay nyajil.", "yundu jina-jina yinyay nyaji-l | you water.gum.tree there see-NONPAST", "r167_present_you_jinajina_there", ["yundu", "jina-jina", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only; no timber/woomera row."),
    row(22, "You see the fig tree there.", "Yundu jarrangkal yinyay nyajil.", "yundu jarrangkal yinyay nyaji-l | you fig.tree there see-NONPAST", "r167_present_you_jarrangkal_there", ["yundu", "jarrangkal", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no fruit/food row."),
    row(23, "You see the scrub tree there.", "Yundu julbin yinyay nyajil.", "yundu julbin yinyay nyaji-l | you scrub.tree there see-NONPAST", "r167_present_you_julbin_there", ["yundu", "julbin", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no edible-processing row."),
    row(24, "You see the kunjarri palm there.", "Yundu kunjarri yinyay nyajil.", "yundu kunjarri yinyay nyaji-l | you palm there see-NONPAST", "r167_present_you_kunjarri_there", ["yundu", "kunjarri", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no bark/container/edible row."),
    row(25, "You see the plum tree there.", "Yundu kurruy yinyay nyajil.", "yundu kurruy yinyay nyaji-l | you plum.tree there see-NONPAST", "r167_present_you_kurruy_there", ["yundu", "kurruy", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no fruit/food row."),
    row(26, "You see the fern tree there.", "Yundu malurri yinyay nyajil.", "yundu malurri yinyay nyaji-l | you fern.tree there see-NONPAST", "r167_present_you_malurri_there", ["yundu", "malurri", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the mawar vine there.", "Yundu mawar yinyay nyajil.", "yundu mawar yinyay nyaji-l | you vine there see-NONPAST", "r167_present_you_mawar_there", ["yundu", "mawar", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no tying/string row."),
    row(28, "You see the maya vine there.", "Yundu maya yinyay nyajil.", "yundu maya yinyay nyaji-l | you vine there see-NONPAST", "r167_present_you_maya_there", ["yundu", "maya", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(29, "You see the wangay vine there.", "Yundu wangay yinyay nyajil.", "yundu wangay yinyay nyaji-l | you vine there see-NONPAST", "r167_present_you_wangay_there", ["yundu", "wangay", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no fruit/place row."),
    row(30, "You see the yawarr palm there.", "Yundu yawarr yinyay nyajil.", "yundu yawarr yinyay nyaji-l | you palm there see-NONPAST", "r167_present_you_yawarr_there", ["yundu", "yawarr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the water gum tree there.", "Jana jina-jina yinyay nyajin.", "jana jina-jina yinyay nyaji-ny | they water.gum.tree there see-PAST", "r167_past_they_jinajina_there", ["jana", "jina-jina", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception; no timber/woomera row."),
    row(32, "They saw the fig tree there.", "Jana jarrangkal yinyay nyajin.", "jana jarrangkal yinyay nyaji-ny | they fig.tree there see-PAST", "r167_past_they_jarrangkal_there", ["jana", "jarrangkal", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/food row."),
    row(33, "They saw the scrub tree there.", "Jana julbin yinyay nyajin.", "jana julbin yinyay nyaji-ny | they scrub.tree there see-PAST", "r167_past_they_julbin_there", ["jana", "julbin", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no edible-processing row."),
    row(34, "They saw the kunjarri palm there.", "Jana kunjarri yinyay nyajin.", "jana kunjarri yinyay nyaji-ny | they palm there see-PAST", "r167_past_they_kunjarri_there", ["jana", "kunjarri", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no bark/container/edible row."),
    row(35, "They saw the plum tree there.", "Jana kurruy yinyay nyajin.", "jana kurruy yinyay nyaji-ny | they plum.tree there see-PAST", "r167_past_they_kurruy_there", ["jana", "kurruy", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/food row."),
    row(36, "They saw the fern tree there.", "Jana malurri yinyay nyajin.", "jana malurri yinyay nyaji-ny | they fern.tree there see-PAST", "r167_past_they_malurri_there", ["jana", "malurri", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(37, "They saw the mawar vine there.", "Jana mawar yinyay nyajin.", "jana mawar yinyay nyaji-ny | they vine there see-PAST", "r167_past_they_mawar_there", ["jana", "mawar", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no tying/string row."),
    row(38, "They saw the maya vine there.", "Jana maya yinyay nyajin.", "jana maya yinyay nyaji-ny | they vine there see-PAST", "r167_past_they_maya_there", ["jana", "maya", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(39, "They saw the wangay vine there.", "Jana wangay yinyay nyajin.", "jana wangay yinyay nyaji-ny | they vine there see-PAST", "r167_past_they_wangay_there", ["jana", "wangay", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/place row."),
    row(40, "They saw the yawarr palm there.", "Jana yawarr yinyay nyajin.", "jana yawarr yinyay nyaji-ny | they palm there see-PAST", "r167_past_they_yawarr_there", ["jana", "yawarr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(41, "We see the water gum tree here.", "Ngana jina-jina yaluy nyajil.", "ngana jina-jina yaluy nyaji-l | we water.gum.tree here see-NONPAST", "r167_present_we_jinajina_here", ["ngana", "jina-jina", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only; no timber/woomera row."),
    row(42, "We see the fig tree here.", "Ngana jarrangkal yaluy nyajil.", "ngana jarrangkal yaluy nyaji-l | we fig.tree here see-NONPAST", "r167_present_we_jarrangkal_here", ["ngana", "jarrangkal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no fruit/food row."),
    row(43, "We see the scrub tree here.", "Ngana julbin yaluy nyajil.", "ngana julbin yaluy nyaji-l | we scrub.tree here see-NONPAST", "r167_present_we_julbin_here", ["ngana", "julbin", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no edible-processing row."),
    row(44, "We see the kunjarri palm here.", "Ngana kunjarri yaluy nyajil.", "ngana kunjarri yaluy nyaji-l | we palm here see-NONPAST", "r167_present_we_kunjarri_here", ["ngana", "kunjarri", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no bark/container/edible row."),
    row(45, "We see the plum tree here.", "Ngana kurruy yaluy nyajil.", "ngana kurruy yaluy nyaji-l | we plum.tree here see-NONPAST", "r167_present_we_kurruy_here", ["ngana", "kurruy", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no fruit/food row."),
    row(46, "We see the fern tree here.", "Ngana malurri yaluy nyajil.", "ngana malurri yaluy nyaji-l | we fern.tree here see-NONPAST", "r167_present_we_malurri_here", ["ngana", "malurri", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(47, "We see the mawar vine here.", "Ngana mawar yaluy nyajil.", "ngana mawar yaluy nyaji-l | we vine here see-NONPAST", "r167_present_we_mawar_here", ["ngana", "mawar", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no tying/string row."),
    row(48, "We see the maya vine here.", "Ngana maya yaluy nyajil.", "ngana maya yaluy nyaji-l | we vine here see-NONPAST", "r167_present_we_maya_here", ["ngana", "maya", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(49, "We see the wangay vine here.", "Ngana wangay yaluy nyajil.", "ngana wangay yaluy nyaji-l | we vine here see-NONPAST", "r167_present_we_wangay_here", ["ngana", "wangay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no fruit/place row."),
    row(50, "We see the yawarr palm here.", "Ngana yawarr yaluy nyajil.", "ngana yawarr yaluy nyaji-l | we palm here see-NONPAST", "r167_present_we_yawarr_here", ["ngana", "yawarr", "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("r167_"):
            issues.append(f"{label}: Rule 167 frame must start with r167_")
        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 167")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied use/homograph 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 167 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 167 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 167 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 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 167 draft: flora reference lexical expansion after Rule 166", "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 167 source pass selected jina-jina, jarrangkal, julbin, kunjarri, kurruy, malurri, mawar, maya, wangay, and yawarr as additional flora reference heads. Dictionary exact readback confirmed the selected senses. Patz readback found no conflicting target use and reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Dakumbar, dukal, jinjay, jalnji, and ngakun were reviewed but not selected because of dialect, fruit/food, poison/nut/gum/spear, or seasonal-signal complications.",
                 command="rg dictionary exact readback; rg grammar readback; sqlite boundary-aware corpus 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 167 is a lexical flora-reference pass for ten bare target heads. It excludes food-processing, fruit, edible-use, medicine, bark use, container-making, spear-making, timber/wood/woomera/material-source, weaving, tying, string/braces, cutting, burning, place-name, target case, target compounds, possession, 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_209.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 Rule 167 flora target per row; all targets bare; no loans; no use/event/homograph tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_209.py static scan", artifact_path="batch_scripts/bank_209.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())
