#!/usr/bin/env python3
"""Bank batch-266: Rule 224 low-coverage named 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-266"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-266-low-coverage-named-tree-reference-lexical-expansion-after-rule223-process.md"

TARGET_HEADS = {
    "jundul": "jundul tree",
    "kabariji": "cherry tree",
    "kawunjil": "black cherry tree",
    "kayjurr": "white gum",
    "kingal": "river oak",
    "kulbar": "white beech",
    "kumin": "kumin fig tree",
    "marbaji": "stringybark tree",
    "milbanku": "pencil cedar",
    "mujarr": "mujarr fig tree",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    # Earlier plant/tree/flora target heads and explicit exclusions.
    "buyukal", "dalkan", "dari", "dibul", "dilbal", "dili", "jabarr", "jakari", "jama", "jilbar",
    "babajaka", "balmbalka", "baway", "bijin", "dalban", "dingki", "dulmbil", "duwar", "kalal", "kumul",
    "jina-jina", "jarrangkal", "julbin", "kunjarri", "kurruy", "malurri", "mawar", "maya", "wangay", "yawarr",
    "jinjajalka", "kurunkal", "madu", "marngkil", "marrabal", "milbarakal", "mungari", "wurmbariji",
    "wuymbariji", "kurrun", "banday", "bijan", "bukunjarra", "bulngkarr", "wanakan", "warka", "wulngkurr",
    "yalngkal", "yarun", "yumba", "buyku", "dakumbar", "jinjay", "jalnji", "ngakun", "mirrbangku",
    "miyilabu", "ngadil", "nyumbil", "marril", "wankar", "yurrunji", "jajikal", "jarrabi", "kabal",
    "nganjirr",
    # Recent non-tree reference targets.
    "kiju", "dakaldakal", "kajarrbi", "kunkun", "kurrija", "ngajay", "nikar", "wakal", "wuli-wuli", "wurrul",
    "kira-kira", "kandal", "kinga", "mulma", "biringal", "birinjil", "kurrmbal", "nganjamu", "kurran",
    "ngirran",
}
DENY_ENGLISH = (
    "fruit", "edible", "food", "seed", "poison", "poisonous", "leach", "leaching", "soak", "soaking",
    "eat", "eating", "eaten", "sweet", "ripe", "ripening", "season", "wet season", "medicine", "bark use",
    "bark-use", "timber", "material", "source", "use", "used", "cut", "cutting", "burn", "burning",
    "gather", "gathering", "grow", "growing", "ecology", "habitat", "beach", "place", "story", "country",
    "ownership", "trunk", "flower", "seasonal",
)


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, 2, js(words), js([]), evidence, "0.86")


EVIDENCE = {
    "jundul": "Dictionary jundul noun 'tree' / jundul tree; poisonous/leaching prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kabariji": "Dictionary kabariji noun 'cherry tree'; fruit prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kawunjil": "Dictionary kawunjil noun 'black cherry tree'; fruit/sweetness/season prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kayjurr": "Dictionary kayjurr noun 'white gum'. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kingal": "Dictionary kingal noun 'river oak'; beach/habitat prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kulbar": "Dictionary kulbar noun 'white beech'; timber/material prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "kumin": "Dictionary kumin noun 'fig tree'; edible fruit/season prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "marbaji": "Dictionary marbaji noun 'stringybark tree'. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "milbanku": "Dictionary milbanku noun 'pencil cedar'; edible seed-skin prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
    "mujarr": "Dictionary mujarr noun 'fig tree'; edible fruit/trunk/colour/season prose not opened. Patz section 3.1 flora noun and section 3.7 deictic support.",
}


ROWS = [
    row(1, "The jundul tree is here.", "Jundul yaluy.", "jundul yaluy | jundul.tree here", "r224_named_tree_ref_here_jundul", ["jundul", "yaluy"], EVIDENCE["jundul"]),
    row(2, "The cherry tree is here.", "Kabariji yaluy.", "kabariji yaluy | cherry.tree here", "r224_named_tree_ref_here_kabariji", ["kabariji", "yaluy"], EVIDENCE["kabariji"]),
    row(3, "The black cherry tree is here.", "Kawunjil yaluy.", "kawunjil yaluy | black.cherry.tree here", "r224_named_tree_ref_here_kawunjil", ["kawunjil", "yaluy"], EVIDENCE["kawunjil"]),
    row(4, "The white gum is here.", "Kayjurr yaluy.", "kayjurr yaluy | white.gum here", "r224_named_tree_ref_here_kayjurr", ["kayjurr", "yaluy"], EVIDENCE["kayjurr"]),
    row(5, "The river oak is here.", "Kingal yaluy.", "kingal yaluy | river.oak here", "r224_named_tree_ref_here_kingal", ["kingal", "yaluy"], EVIDENCE["kingal"]),
    row(6, "The white beech is here.", "Kulbar yaluy.", "kulbar yaluy | white.beech here", "r224_named_tree_ref_here_kulbar", ["kulbar", "yaluy"], EVIDENCE["kulbar"]),
    row(7, "The kumin fig tree is here.", "Kumin yaluy.", "kumin yaluy | kumin.fig.tree here", "r224_named_tree_ref_here_kumin", ["kumin", "yaluy"], EVIDENCE["kumin"]),
    row(8, "The stringybark tree is here.", "Marbaji yaluy.", "marbaji yaluy | stringybark.tree here", "r224_named_tree_ref_here_marbaji", ["marbaji", "yaluy"], EVIDENCE["marbaji"]),
    row(9, "The pencil cedar is here.", "Milbanku yaluy.", "milbanku yaluy | pencil.cedar here", "r224_named_tree_ref_here_milbanku", ["milbanku", "yaluy"], EVIDENCE["milbanku"]),
    row(10, "The mujarr fig tree is here.", "Mujarr yaluy.", "mujarr yaluy | mujarr.fig.tree here", "r224_named_tree_ref_here_mujarr", ["mujarr", "yaluy"], EVIDENCE["mujarr"]),
    row(11, "The jundul tree is there.", "Jundul yinyay.", "jundul yinyay | jundul.tree there", "r224_named_tree_ref_there_jundul", ["jundul", "yinyay"], EVIDENCE["jundul"]),
    row(12, "The cherry tree is there.", "Kabariji yinyay.", "kabariji yinyay | cherry.tree there", "r224_named_tree_ref_there_kabariji", ["kabariji", "yinyay"], EVIDENCE["kabariji"]),
    row(13, "The black cherry tree is there.", "Kawunjil yinyay.", "kawunjil yinyay | black.cherry.tree there", "r224_named_tree_ref_there_kawunjil", ["kawunjil", "yinyay"], EVIDENCE["kawunjil"]),
    row(14, "The white gum is there.", "Kayjurr yinyay.", "kayjurr yinyay | white.gum there", "r224_named_tree_ref_there_kayjurr", ["kayjurr", "yinyay"], EVIDENCE["kayjurr"]),
    row(15, "The river oak is there.", "Kingal yinyay.", "kingal yinyay | river.oak there", "r224_named_tree_ref_there_kingal", ["kingal", "yinyay"], EVIDENCE["kingal"]),
    row(16, "The white beech is there.", "Kulbar yinyay.", "kulbar yinyay | white.beech there", "r224_named_tree_ref_there_kulbar", ["kulbar", "yinyay"], EVIDENCE["kulbar"]),
    row(17, "The kumin fig tree is there.", "Kumin yinyay.", "kumin yinyay | kumin.fig.tree there", "r224_named_tree_ref_there_kumin", ["kumin", "yinyay"], EVIDENCE["kumin"]),
    row(18, "The stringybark tree is there.", "Marbaji yinyay.", "marbaji yinyay | stringybark.tree there", "r224_named_tree_ref_there_marbaji", ["marbaji", "yinyay"], EVIDENCE["marbaji"]),
    row(19, "The pencil cedar is there.", "Milbanku yinyay.", "milbanku yinyay | pencil.cedar there", "r224_named_tree_ref_there_milbanku", ["milbanku", "yinyay"], EVIDENCE["milbanku"]),
    row(20, "The mujarr fig tree is there.", "Mujarr yinyay.", "mujarr yinyay | mujarr.fig.tree there", "r224_named_tree_ref_there_mujarr", ["mujarr", "yinyay"], EVIDENCE["mujarr"]),
    row(21, "That jundul tree is there.", "Yinya jundul yinyay.", "yinya jundul yinyay | that jundul.tree there", "r224_that_named_tree_ref_there_jundul", ["yinya", "jundul", "yinyay"], EVIDENCE["jundul"]),
    row(22, "That cherry tree is there.", "Yinya kabariji yinyay.", "yinya kabariji yinyay | that cherry.tree there", "r224_that_named_tree_ref_there_kabariji", ["yinya", "kabariji", "yinyay"], EVIDENCE["kabariji"]),
    row(23, "That black cherry tree is there.", "Yinya kawunjil yinyay.", "yinya kawunjil yinyay | that black.cherry.tree there", "r224_that_named_tree_ref_there_kawunjil", ["yinya", "kawunjil", "yinyay"], EVIDENCE["kawunjil"]),
    row(24, "That white gum is there.", "Yinya kayjurr yinyay.", "yinya kayjurr yinyay | that white.gum there", "r224_that_named_tree_ref_there_kayjurr", ["yinya", "kayjurr", "yinyay"], EVIDENCE["kayjurr"]),
    row(25, "That river oak is there.", "Yinya kingal yinyay.", "yinya kingal yinyay | that river.oak there", "r224_that_named_tree_ref_there_kingal", ["yinya", "kingal", "yinyay"], EVIDENCE["kingal"]),
    row(26, "That white beech is there.", "Yinya kulbar yinyay.", "yinya kulbar yinyay | that white.beech there", "r224_that_named_tree_ref_there_kulbar", ["yinya", "kulbar", "yinyay"], EVIDENCE["kulbar"]),
    row(27, "That kumin fig tree is there.", "Yinya kumin yinyay.", "yinya kumin yinyay | that kumin.fig.tree there", "r224_that_named_tree_ref_there_kumin", ["yinya", "kumin", "yinyay"], EVIDENCE["kumin"]),
    row(28, "That stringybark tree is there.", "Yinya marbaji yinyay.", "yinya marbaji yinyay | that stringybark.tree there", "r224_that_named_tree_ref_there_marbaji", ["yinya", "marbaji", "yinyay"], EVIDENCE["marbaji"]),
    row(29, "That pencil cedar is there.", "Yinya milbanku yinyay.", "yinya milbanku yinyay | that pencil.cedar there", "r224_that_named_tree_ref_there_milbanku", ["yinya", "milbanku", "yinyay"], EVIDENCE["milbanku"]),
    row(30, "That mujarr fig tree is there.", "Yinya mujarr yinyay.", "yinya mujarr yinyay | that mujarr.fig.tree there", "r224_that_named_tree_ref_there_mujarr", ["yinya", "mujarr", "yinyay"], EVIDENCE["mujarr"]),
    row(31, "That jundul tree is there.", "Jundul yinya yinyay.", "jundul yinya yinyay | that jundul.tree there", "r224_named_tree_that_there_jundul", ["jundul", "yinya", "yinyay"], EVIDENCE["jundul"]),
    row(32, "That cherry tree is there.", "Kabariji yinya yinyay.", "kabariji yinya yinyay | that cherry.tree there", "r224_named_tree_that_there_kabariji", ["kabariji", "yinya", "yinyay"], EVIDENCE["kabariji"]),
    row(33, "That black cherry tree is there.", "Kawunjil yinya yinyay.", "kawunjil yinya yinyay | that black.cherry.tree there", "r224_named_tree_that_there_kawunjil", ["kawunjil", "yinya", "yinyay"], EVIDENCE["kawunjil"]),
    row(34, "That white gum is there.", "Kayjurr yinya yinyay.", "kayjurr yinya yinyay | that white.gum there", "r224_named_tree_that_there_kayjurr", ["kayjurr", "yinya", "yinyay"], EVIDENCE["kayjurr"]),
    row(35, "That river oak is there.", "Kingal yinya yinyay.", "kingal yinya yinyay | that river.oak there", "r224_named_tree_that_there_kingal", ["kingal", "yinya", "yinyay"], EVIDENCE["kingal"]),
    row(36, "That white beech is there.", "Kulbar yinya yinyay.", "kulbar yinya yinyay | that white.beech there", "r224_named_tree_that_there_kulbar", ["kulbar", "yinya", "yinyay"], EVIDENCE["kulbar"]),
    row(37, "That kumin fig tree is there.", "Kumin yinya yinyay.", "kumin yinya yinyay | that kumin.fig.tree there", "r224_named_tree_that_there_kumin", ["kumin", "yinya", "yinyay"], EVIDENCE["kumin"]),
    row(38, "That stringybark tree is there.", "Marbaji yinya yinyay.", "marbaji yinya yinyay | that stringybark.tree there", "r224_named_tree_that_there_marbaji", ["marbaji", "yinya", "yinyay"], EVIDENCE["marbaji"]),
    row(39, "That pencil cedar is there.", "Milbanku yinya yinyay.", "milbanku yinya yinyay | that pencil.cedar there", "r224_named_tree_that_there_milbanku", ["milbanku", "yinya", "yinyay"], EVIDENCE["milbanku"]),
    row(40, "That mujarr fig tree is there.", "Mujarr yinya yinyay.", "mujarr yinya yinyay | that mujarr.fig.tree there", "r224_named_tree_that_there_mujarr", ["mujarr", "yinya", "yinyay"], EVIDENCE["mujarr"]),
    row(41, "That jundul tree is here.", "Yinya jundul yaluy.", "yinya jundul yaluy | that jundul.tree here", "r224_that_named_tree_ref_here_jundul", ["yinya", "jundul", "yaluy"], EVIDENCE["jundul"]),
    row(42, "That cherry tree is here.", "Yinya kabariji yaluy.", "yinya kabariji yaluy | that cherry.tree here", "r224_that_named_tree_ref_here_kabariji", ["yinya", "kabariji", "yaluy"], EVIDENCE["kabariji"]),
    row(43, "That black cherry tree is here.", "Yinya kawunjil yaluy.", "yinya kawunjil yaluy | that black.cherry.tree here", "r224_that_named_tree_ref_here_kawunjil", ["yinya", "kawunjil", "yaluy"], EVIDENCE["kawunjil"]),
    row(44, "That white gum is here.", "Yinya kayjurr yaluy.", "yinya kayjurr yaluy | that white.gum here", "r224_that_named_tree_ref_here_kayjurr", ["yinya", "kayjurr", "yaluy"], EVIDENCE["kayjurr"]),
    row(45, "That river oak is here.", "Yinya kingal yaluy.", "yinya kingal yaluy | that river.oak here", "r224_that_named_tree_ref_here_kingal", ["yinya", "kingal", "yaluy"], EVIDENCE["kingal"]),
    row(46, "That white beech is here.", "Yinya kulbar yaluy.", "yinya kulbar yaluy | that white.beech here", "r224_that_named_tree_ref_here_kulbar", ["yinya", "kulbar", "yaluy"], EVIDENCE["kulbar"]),
    row(47, "That kumin fig tree is here.", "Yinya kumin yaluy.", "yinya kumin yaluy | that kumin.fig.tree here", "r224_that_named_tree_ref_here_kumin", ["yinya", "kumin", "yaluy"], EVIDENCE["kumin"]),
    row(48, "That stringybark tree is here.", "Yinya marbaji yaluy.", "yinya marbaji yaluy | that stringybark.tree here", "r224_that_named_tree_ref_here_marbaji", ["yinya", "marbaji", "yaluy"], EVIDENCE["marbaji"]),
    row(49, "That pencil cedar is here.", "Yinya milbanku yaluy.", "yinya milbanku yaluy | that pencil.cedar here", "r224_that_named_tree_ref_here_milbanku", ["yinya", "milbanku", "yaluy"], EVIDENCE["milbanku"]),
    row(50, "That mujarr fig tree is here.", "Yinya mujarr yaluy.", "yinya mujarr yaluy | that mujarr.fig.tree here", "r224_that_named_tree_ref_here_mujarr", ["yinya", "mujarr", "yaluy"], EVIDENCE["mujarr"]),
]


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


def has_target_morphology(low: str, head: str) -> bool:
    suffixes = "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|baja|bungal|bungan|mal|man|rriny"
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:{suffixes})\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.strip())}\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("r224_"):
            issues.append(f"{label}: Rule 224 frame must start with r224_")
        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 224")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied carry-forward 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 224 target noun, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            dotted = selected.replace("-", ".").replace(" ", ".")
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected not in analysis and dotted not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        for support in SUPPORT:
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if 1 <= seq <= 10 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.") or len(low.split()) != 2):
            issues.append(f"{label}: rows 1-10 require TARGET yaluy")
        if 11 <= seq <= 20 and (has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 2):
            issues.append(f"{label}: rows 11-20 require TARGET yinyay")
        if 21 <= seq <= 30 and (not low.startswith("yinya ") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 21-30 require Yinya TARGET yinyay")
        if 31 <= seq <= 40 and (not has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 3 or low.startswith("yinya ")):
            issues.append(f"{label}: rows 31-40 require TARGET yinya yinyay")
        if 41 <= seq <= 50 and (not low.startswith("yinya ") or has_token(low, "yinyay") or not low.endswith(" yaluy.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 41-50 require Yinya TARGET yaluy")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied tree-use/food/material/habitat/source-prose 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,))
    else:
        db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 224 draft", "operator-guide-2026-07-08", "draft under review", NOW),
        )
        batch_id = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()[0]

    collisions: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        found = db.execute(
            """
            SELECT b.label, s.seq, s.status
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(s.kuku)=lower(?) AND s.status IN ('accepted','revised','under_review')
            """,
            (kuku,),
        ).fetchall()
        if found:
            collisions.append(f"{seq:02d} {kuku}: {found}")
    if collisions:
        raise SystemExit("duplicate preflight failed:\n" + "\n".join(collisions))

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail="Checked Patz section 3.1 noun/flora basis, Patz section 3.7 yinya/yaluy/yinyay support, earlier plant/tree/flora rules, and dictionary entries for jundul, kabariji, kawunjil, kayjurr, kingal, kulbar, kumin, marbaji, milbanku, and mujarr. Admitted only selected bare named-tree-reference labels.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail="Selected a low-coverage named-tree-reference field after excluding previous tree/flora target heads, place-heavy candidates, exact-collision candidates kabal/nganjirr, fruit/food/seed/poison/leaching-heavy prose, medicine, bark-use, timber/material-source, ecology, place/story/country, and all use/event/source-prose semantics.",
        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 over all 50 planned Rule 224 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        artifact_path="batch_scripts/bank_266.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="bank_266.py static guards passed: 50 explicit hand-authored rows, exactly one named-tree-reference target noun per row, no loans, no target morphology, no tree-use/food/material/habitat/source-prose English, and only the five sourced deictic frame bands.",
        artifact_path="batch_scripts/bank_266.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, NOW, NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

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


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