#!/usr/bin/env python3
"""Bank batch-356: Rule 314 visible tree/palm singular/third-person past perception."""

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-356"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-356-visible-tree-palm-singular-third-past-perception-after-rule313-process.md"

TARGET_EVIDENCE = {
    "dulmbi": "Dictionary yaml lines 6478-6490 give dulmbi as noun 'umbrella palm' and also a place name at Stucky's Gap. Rule 314 selects visible umbrella-palm reference only and leaves place-name use closed.",
    "kakaji": "Dictionary yaml lines 12087-12109 give kakaji as noun 'mangrove tree' / 'mangrove' with source prose about fruit made edible by leaching poison. Rule 314 selects visible kakaji mangrove-tree reference only and leaves fruit, leaching, poison, shore, tide, use, and ecology rows closed.",
    "mukukanka": "Dictionary yaml lines 20286-20300 give mukukanka as noun 'tree' with source prose about edible fruit ripening in August-September. Rule 314 selects visible mukukanka-tree reference only and leaves fruit, edible, food, season, ripening, month, and use rows closed.",
    "murrkul": "Dictionary yaml lines 21058-21070 give murrkul as noun 'tree' with source prose about edible fruit. Rule 314 selects visible murrkul-tree reference only and leaves fruit, edible, food, seed, season, and use rows closed.",
    "milbarkal": "Dictionary yaml lines 18981-18990 give milbarkal as noun 'tree', English name unknown. Rule 314 selects visible milbarkal-tree reference only.",
    "mirrbangku": "Dictionary yaml lines 19739-19760 give mirrbangku as noun 'tree' / 'pencil cedar' with source prose about date-shaped sweet fruit. Rule 314 selects visible pencil-cedar-tree reference only and leaves fruit, date-shape, sweetness, and food rows closed.",
    "mura": "Dictionary yaml lines 20890-20910 give mura as noun 'tree', including source prose that blooming marks the time for minya jalan. Rule 314 selects visible mura-tree reference only and leaves bloom, seasonal timing, minya jalan, and event rows closed.",
    "ngadil": "Dictionary yaml lines 21677-21697 give ngadil as noun 'tree' / 'hickory' with source prose about good timber for woomeras. Rule 314 selects visible hickory-tree reference only and leaves timber, woomera, and material-use rows closed.",
    "nyumbil": "Dictionary yaml lines 24727-24748 give nyumbil as noun 'tree' / 'coolibah tree', with a separate homographic leech entry. Rule 314 selects visible coolibah-tree reference only and leaves leech/fauna homograph rows closed.",
    "wankar": "Dictionary yaml lines 26184-26206 give wankar as noun 'tree' with source prose about water-side growth, red flowers, and a necklace made from seeds. Rule 314 selects visible wankar-tree reference only and leaves water-side ecology, flowers, seed, necklace, and artefact rows closed.",
}

SUPPORT_EVIDENCE = (
    "Living grammar pronoun table lines 2577-2582 source bare nominatives ngayu, yundu, nyulu, bula, and jana "
    "with non-nominative case forms separated in the same table; line 2686 discusses third-person jana/bula; "
    "demonstrative lines 2834-2845 source yaluy 'here' and yinyay 'there'; grammar example 119 gives nyaji-ny "
    "as 'see-PAST', and lines 3160-3162 identify past -ny. Dictionary usage lines 23882-23883 and 23975-23976 "
    "independently attest running-form nyajin in complete perception clauses. Rule 314 uses only bare support "
    "forms and the dictionary-attested nyajin orthography for Patz's segmented nyaji-ny."
)

TARGET_ORDER = ["dulmbi", "kakaji", "mukukanka", "murrkul", "milbarkal", "mirrbangku", "mura", "ngadil", "nyumbil", "wankar"]
FRAME_SPECS = [
    ("ngayu", "yaluy"),
    ("yundu", "yinyay"),
    ("nyulu", "yaluy"),
    ("bula", "yinyay"),
    ("jana", "yaluy"),
]

DENY_KUKU = {
    "nganya", "yununy", "nyunguny", "yununiny", "nyunguniny", "ngaykunku", "yununku",
    "nyungunku", "ngaykundu", "yunundu", "nyungundu", "ngaykundumuny", "yunundumuny",
    "nyungundumuny", "ngaykunji", "yununji", "nyungunji", "ngayku", "yunu", "nyunju",
    "ngali", "ngaliny", "yubal", "yurra", "ngana", "nganjin", "yulu", "iana",
    "bulangan", "bulaniny", "bulanka", "bulanda", "bulandamuny", "bulanji", "bulanga",
    "ianangan", "iananiny", "iananka", "iananda", "ianandamuny", "iananji", "iananga",
    "bujabay", "jingajalka", "jirimandi", "julbal", "jungka", "karranda", "karrandal",
    "kawarr", "marril", "ngurrkul", "jinajina", "kuraykuray", "luku",
    "yalungku", "yaluyngku", "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajil", "nyajiny", "nyaji-l", "nyaji-ny", "nyaji-nka", "nyaji-l-nyaji", "milka", "baykal", "jalngkay",
}
DENY_ENGLISH = (
    "place", "stucky", "gap", "timber", "woomera", "woomeras", "dialect", "use", "used", "using",
    "fruit", "date", "sweet", "sweetness", "food", "edible", "bloom", "blooming", "season", "time",
    "august", "september", "ripe", "ripening", "month", "minya", "jalan", "pair", "dual", "leech",
    "fauna", "water-side", "waterside", "water side", "shore", "tide", "poison", "leaching", "ecology",
    "flower", "flowers", "seed", "seeds", "necklace", "string", "threaded", "artefact", "material",
    "source", "story", "red", "black",
)


def count_words(db: sqlite3.Connection, words: list[str]) -> dict[str, int]:
    return {
        word: db.execute(
            """
            SELECT COUNT(*)
            FROM sentences s
            WHERE s.status IN ('accepted','revised')
              AND EXISTS (SELECT 1 FROM json_each(s.words_used) WHERE value=?)
            """,
            (word,),
        ).fetchone()[0]
        for word in words
    }


def row(seq: int, english: str, kuku: str, analysis: str, frame: str, words: list[str]) -> tuple:
    target = words[1]
    evidence = f"{TARGET_EVIDENCE[target]} {SUPPORT_EVIDENCE}"
    return (seq, english, kuku, analysis, frame, 3, json.dumps(words, ensure_ascii=False), json.dumps([], ensure_ascii=False), evidence, "0.86")


ROWS = [
    row(1, "I saw the dulmbi umbrella palm here.", "Ngayu dulmbi yaluy nyajin.", "ngayu dulmbi yaluy nyajin | 1sg.NOM dulmbi.umbrella.palm here see.PST", "r314_1sg_here_tree_saw_dulmbi", ["ngayu", "dulmbi", "yaluy", "nyajin"]),
    row(2, "I saw the kakaji mangrove tree here.", "Ngayu kakaji yaluy nyajin.", "ngayu kakaji yaluy nyajin | 1sg.NOM kakaji.mangrove.tree here see.PST", "r314_1sg_here_tree_saw_kakaji", ["ngayu", "kakaji", "yaluy", "nyajin"]),
    row(3, "I saw the mukukanka tree here.", "Ngayu mukukanka yaluy nyajin.", "ngayu mukukanka yaluy nyajin | 1sg.NOM mukukanka.tree here see.PST", "r314_1sg_here_tree_saw_mukukanka", ["ngayu", "mukukanka", "yaluy", "nyajin"]),
    row(4, "I saw the murrkul tree here.", "Ngayu murrkul yaluy nyajin.", "ngayu murrkul yaluy nyajin | 1sg.NOM murrkul.tree here see.PST", "r314_1sg_here_tree_saw_murrkul", ["ngayu", "murrkul", "yaluy", "nyajin"]),
    row(5, "I saw the milbarkal tree here.", "Ngayu milbarkal yaluy nyajin.", "ngayu milbarkal yaluy nyajin | 1sg.NOM milbarkal.tree here see.PST", "r314_1sg_here_tree_saw_milbarkal", ["ngayu", "milbarkal", "yaluy", "nyajin"]),
    row(6, "I saw the mirrbangku pencil cedar tree here.", "Ngayu mirrbangku yaluy nyajin.", "ngayu mirrbangku yaluy nyajin | 1sg.NOM mirrbangku.pencil.cedar.tree here see.PST", "r314_1sg_here_tree_saw_mirrbangku", ["ngayu", "mirrbangku", "yaluy", "nyajin"]),
    row(7, "I saw the mura tree here.", "Ngayu mura yaluy nyajin.", "ngayu mura yaluy nyajin | 1sg.NOM mura.tree here see.PST", "r314_1sg_here_tree_saw_mura", ["ngayu", "mura", "yaluy", "nyajin"]),
    row(8, "I saw the ngadil hickory tree here.", "Ngayu ngadil yaluy nyajin.", "ngayu ngadil yaluy nyajin | 1sg.NOM ngadil.hickory.tree here see.PST", "r314_1sg_here_tree_saw_ngadil", ["ngayu", "ngadil", "yaluy", "nyajin"]),
    row(9, "I saw the nyumbil coolibah tree here.", "Ngayu nyumbil yaluy nyajin.", "ngayu nyumbil yaluy nyajin | 1sg.NOM nyumbil.coolibah.tree here see.PST", "r314_1sg_here_tree_saw_nyumbil", ["ngayu", "nyumbil", "yaluy", "nyajin"]),
    row(10, "I saw the wankar tree here.", "Ngayu wankar yaluy nyajin.", "ngayu wankar yaluy nyajin | 1sg.NOM wankar.tree here see.PST", "r314_1sg_here_tree_saw_wankar", ["ngayu", "wankar", "yaluy", "nyajin"]),
    row(11, "You saw the dulmbi umbrella palm there.", "Yundu dulmbi yinyay nyajin.", "yundu dulmbi yinyay nyajin | 2sg.NOM dulmbi.umbrella.palm there see.PST", "r314_2sg_there_tree_saw_dulmbi", ["yundu", "dulmbi", "yinyay", "nyajin"]),
    row(12, "You saw the kakaji mangrove tree there.", "Yundu kakaji yinyay nyajin.", "yundu kakaji yinyay nyajin | 2sg.NOM kakaji.mangrove.tree there see.PST", "r314_2sg_there_tree_saw_kakaji", ["yundu", "kakaji", "yinyay", "nyajin"]),
    row(13, "You saw the mukukanka tree there.", "Yundu mukukanka yinyay nyajin.", "yundu mukukanka yinyay nyajin | 2sg.NOM mukukanka.tree there see.PST", "r314_2sg_there_tree_saw_mukukanka", ["yundu", "mukukanka", "yinyay", "nyajin"]),
    row(14, "You saw the murrkul tree there.", "Yundu murrkul yinyay nyajin.", "yundu murrkul yinyay nyajin | 2sg.NOM murrkul.tree there see.PST", "r314_2sg_there_tree_saw_murrkul", ["yundu", "murrkul", "yinyay", "nyajin"]),
    row(15, "You saw the milbarkal tree there.", "Yundu milbarkal yinyay nyajin.", "yundu milbarkal yinyay nyajin | 2sg.NOM milbarkal.tree there see.PST", "r314_2sg_there_tree_saw_milbarkal", ["yundu", "milbarkal", "yinyay", "nyajin"]),
    row(16, "You saw the mirrbangku pencil cedar tree there.", "Yundu mirrbangku yinyay nyajin.", "yundu mirrbangku yinyay nyajin | 2sg.NOM mirrbangku.pencil.cedar.tree there see.PST", "r314_2sg_there_tree_saw_mirrbangku", ["yundu", "mirrbangku", "yinyay", "nyajin"]),
    row(17, "You saw the mura tree there.", "Yundu mura yinyay nyajin.", "yundu mura yinyay nyajin | 2sg.NOM mura.tree there see.PST", "r314_2sg_there_tree_saw_mura", ["yundu", "mura", "yinyay", "nyajin"]),
    row(18, "You saw the ngadil hickory tree there.", "Yundu ngadil yinyay nyajin.", "yundu ngadil yinyay nyajin | 2sg.NOM ngadil.hickory.tree there see.PST", "r314_2sg_there_tree_saw_ngadil", ["yundu", "ngadil", "yinyay", "nyajin"]),
    row(19, "You saw the nyumbil coolibah tree there.", "Yundu nyumbil yinyay nyajin.", "yundu nyumbil yinyay nyajin | 2sg.NOM nyumbil.coolibah.tree there see.PST", "r314_2sg_there_tree_saw_nyumbil", ["yundu", "nyumbil", "yinyay", "nyajin"]),
    row(20, "You saw the wankar tree there.", "Yundu wankar yinyay nyajin.", "yundu wankar yinyay nyajin | 2sg.NOM wankar.tree there see.PST", "r314_2sg_there_tree_saw_wankar", ["yundu", "wankar", "yinyay", "nyajin"]),
    row(21, "He saw the dulmbi umbrella palm here.", "Nyulu dulmbi yaluy nyajin.", "nyulu dulmbi yaluy nyajin | 3sg.NOM dulmbi.umbrella.palm here see.PST", "r314_3sg_here_tree_saw_dulmbi", ["nyulu", "dulmbi", "yaluy", "nyajin"]),
    row(22, "He saw the kakaji mangrove tree here.", "Nyulu kakaji yaluy nyajin.", "nyulu kakaji yaluy nyajin | 3sg.NOM kakaji.mangrove.tree here see.PST", "r314_3sg_here_tree_saw_kakaji", ["nyulu", "kakaji", "yaluy", "nyajin"]),
    row(23, "He saw the mukukanka tree here.", "Nyulu mukukanka yaluy nyajin.", "nyulu mukukanka yaluy nyajin | 3sg.NOM mukukanka.tree here see.PST", "r314_3sg_here_tree_saw_mukukanka", ["nyulu", "mukukanka", "yaluy", "nyajin"]),
    row(24, "He saw the murrkul tree here.", "Nyulu murrkul yaluy nyajin.", "nyulu murrkul yaluy nyajin | 3sg.NOM murrkul.tree here see.PST", "r314_3sg_here_tree_saw_murrkul", ["nyulu", "murrkul", "yaluy", "nyajin"]),
    row(25, "He saw the milbarkal tree here.", "Nyulu milbarkal yaluy nyajin.", "nyulu milbarkal yaluy nyajin | 3sg.NOM milbarkal.tree here see.PST", "r314_3sg_here_tree_saw_milbarkal", ["nyulu", "milbarkal", "yaluy", "nyajin"]),
    row(26, "He saw the mirrbangku pencil cedar tree here.", "Nyulu mirrbangku yaluy nyajin.", "nyulu mirrbangku yaluy nyajin | 3sg.NOM mirrbangku.pencil.cedar.tree here see.PST", "r314_3sg_here_tree_saw_mirrbangku", ["nyulu", "mirrbangku", "yaluy", "nyajin"]),
    row(27, "He saw the mura tree here.", "Nyulu mura yaluy nyajin.", "nyulu mura yaluy nyajin | 3sg.NOM mura.tree here see.PST", "r314_3sg_here_tree_saw_mura", ["nyulu", "mura", "yaluy", "nyajin"]),
    row(28, "He saw the ngadil hickory tree here.", "Nyulu ngadil yaluy nyajin.", "nyulu ngadil yaluy nyajin | 3sg.NOM ngadil.hickory.tree here see.PST", "r314_3sg_here_tree_saw_ngadil", ["nyulu", "ngadil", "yaluy", "nyajin"]),
    row(29, "He saw the nyumbil coolibah tree here.", "Nyulu nyumbil yaluy nyajin.", "nyulu nyumbil yaluy nyajin | 3sg.NOM nyumbil.coolibah.tree here see.PST", "r314_3sg_here_tree_saw_nyumbil", ["nyulu", "nyumbil", "yaluy", "nyajin"]),
    row(30, "He saw the wankar tree here.", "Nyulu wankar yaluy nyajin.", "nyulu wankar yaluy nyajin | 3sg.NOM wankar.tree here see.PST", "r314_3sg_here_tree_saw_wankar", ["nyulu", "wankar", "yaluy", "nyajin"]),
    row(31, "The two of them saw the dulmbi umbrella palm there.", "Bula dulmbi yinyay nyajin.", "bula dulmbi yinyay nyajin | 3du.NOM dulmbi.umbrella.palm there see.PST", "r314_3du_there_tree_saw_dulmbi", ["bula", "dulmbi", "yinyay", "nyajin"]),
    row(32, "The two of them saw the kakaji mangrove tree there.", "Bula kakaji yinyay nyajin.", "bula kakaji yinyay nyajin | 3du.NOM kakaji.mangrove.tree there see.PST", "r314_3du_there_tree_saw_kakaji", ["bula", "kakaji", "yinyay", "nyajin"]),
    row(33, "The two of them saw the mukukanka tree there.", "Bula mukukanka yinyay nyajin.", "bula mukukanka yinyay nyajin | 3du.NOM mukukanka.tree there see.PST", "r314_3du_there_tree_saw_mukukanka", ["bula", "mukukanka", "yinyay", "nyajin"]),
    row(34, "The two of them saw the murrkul tree there.", "Bula murrkul yinyay nyajin.", "bula murrkul yinyay nyajin | 3du.NOM murrkul.tree there see.PST", "r314_3du_there_tree_saw_murrkul", ["bula", "murrkul", "yinyay", "nyajin"]),
    row(35, "The two of them saw the milbarkal tree there.", "Bula milbarkal yinyay nyajin.", "bula milbarkal yinyay nyajin | 3du.NOM milbarkal.tree there see.PST", "r314_3du_there_tree_saw_milbarkal", ["bula", "milbarkal", "yinyay", "nyajin"]),
    row(36, "The two of them saw the mirrbangku pencil cedar tree there.", "Bula mirrbangku yinyay nyajin.", "bula mirrbangku yinyay nyajin | 3du.NOM mirrbangku.pencil.cedar.tree there see.PST", "r314_3du_there_tree_saw_mirrbangku", ["bula", "mirrbangku", "yinyay", "nyajin"]),
    row(37, "The two of them saw the mura tree there.", "Bula mura yinyay nyajin.", "bula mura yinyay nyajin | 3du.NOM mura.tree there see.PST", "r314_3du_there_tree_saw_mura", ["bula", "mura", "yinyay", "nyajin"]),
    row(38, "The two of them saw the ngadil hickory tree there.", "Bula ngadil yinyay nyajin.", "bula ngadil yinyay nyajin | 3du.NOM ngadil.hickory.tree there see.PST", "r314_3du_there_tree_saw_ngadil", ["bula", "ngadil", "yinyay", "nyajin"]),
    row(39, "The two of them saw the nyumbil coolibah tree there.", "Bula nyumbil yinyay nyajin.", "bula nyumbil yinyay nyajin | 3du.NOM nyumbil.coolibah.tree there see.PST", "r314_3du_there_tree_saw_nyumbil", ["bula", "nyumbil", "yinyay", "nyajin"]),
    row(40, "The two of them saw the wankar tree there.", "Bula wankar yinyay nyajin.", "bula wankar yinyay nyajin | 3du.NOM wankar.tree there see.PST", "r314_3du_there_tree_saw_wankar", ["bula", "wankar", "yinyay", "nyajin"]),
    row(41, "They saw the dulmbi umbrella palm here.", "Jana dulmbi yaluy nyajin.", "jana dulmbi yaluy nyajin | 3pl.NOM dulmbi.umbrella.palm here see.PST", "r314_3pl_here_tree_saw_dulmbi", ["jana", "dulmbi", "yaluy", "nyajin"]),
    row(42, "They saw the kakaji mangrove tree here.", "Jana kakaji yaluy nyajin.", "jana kakaji yaluy nyajin | 3pl.NOM kakaji.mangrove.tree here see.PST", "r314_3pl_here_tree_saw_kakaji", ["jana", "kakaji", "yaluy", "nyajin"]),
    row(43, "They saw the mukukanka tree here.", "Jana mukukanka yaluy nyajin.", "jana mukukanka yaluy nyajin | 3pl.NOM mukukanka.tree here see.PST", "r314_3pl_here_tree_saw_mukukanka", ["jana", "mukukanka", "yaluy", "nyajin"]),
    row(44, "They saw the murrkul tree here.", "Jana murrkul yaluy nyajin.", "jana murrkul yaluy nyajin | 3pl.NOM murrkul.tree here see.PST", "r314_3pl_here_tree_saw_murrkul", ["jana", "murrkul", "yaluy", "nyajin"]),
    row(45, "They saw the milbarkal tree here.", "Jana milbarkal yaluy nyajin.", "jana milbarkal yaluy nyajin | 3pl.NOM milbarkal.tree here see.PST", "r314_3pl_here_tree_saw_milbarkal", ["jana", "milbarkal", "yaluy", "nyajin"]),
    row(46, "They saw the mirrbangku pencil cedar tree here.", "Jana mirrbangku yaluy nyajin.", "jana mirrbangku yaluy nyajin | 3pl.NOM mirrbangku.pencil.cedar.tree here see.PST", "r314_3pl_here_tree_saw_mirrbangku", ["jana", "mirrbangku", "yaluy", "nyajin"]),
    row(47, "They saw the mura tree here.", "Jana mura yaluy nyajin.", "jana mura yaluy nyajin | 3pl.NOM mura.tree here see.PST", "r314_3pl_here_tree_saw_mura", ["jana", "mura", "yaluy", "nyajin"]),
    row(48, "They saw the ngadil hickory tree here.", "Jana ngadil yaluy nyajin.", "jana ngadil yaluy nyajin | 3pl.NOM ngadil.hickory.tree here see.PST", "r314_3pl_here_tree_saw_ngadil", ["jana", "ngadil", "yaluy", "nyajin"]),
    row(49, "They saw the nyumbil coolibah tree here.", "Jana nyumbil yaluy nyajin.", "jana nyumbil yaluy nyajin | 3pl.NOM nyumbil.coolibah.tree here see.PST", "r314_3pl_here_tree_saw_nyumbil", ["jana", "nyumbil", "yaluy", "nyajin"]),
    row(50, "They saw the wankar tree here.", "Jana wankar yaluy nyajin.", "jana wankar yaluy nyajin | 3pl.NOM wankar.tree here see.PST", "r314_3pl_here_tree_saw_wankar", ["jana", "wankar", "yaluy", "nyajin"]),
]


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"row count {len(ROWS)} != 50")
    if [r[0] for r in ROWS] != list(range(1, 51)):
        issues.append("sequence is not 1..50")
    kukus = [r[2] for r in ROWS]
    if len(set(kukus)) != len(kukus):
        issues.append("duplicate Kuku surface inside batch")
    for seq, english, kuku, _analysis, frame, _tier, words_json, loans_json, _evidence, _confidence in ROWS:
        words = json.loads(words_json)
        loans = json.loads(loans_json)
        lower_kuku = kuku.lower()
        lower_english = english.lower()
        if loans:
            issues.append(f"{seq}: loans used {loans}")
        denied = sorted({w for w in DENY_KUKU if re.search(rf"(^|\s){re.escape(w)}([\s\.]|$)", lower_kuku)})
        if denied:
            issues.append(f"{seq}: denied Kuku forms {denied}")
        denied_english = [term for term in DENY_ENGLISH if re.search(rf"\b{re.escape(term.strip())}\b", lower_english)]
        if denied_english:
            issues.append(f"{seq}: denied English drift {denied_english}")
        if " saw " not in f" {lower_english} ":
            issues.append(f"{seq}: English is not past saw")
        target_hits = [w for w in TARGET_ORDER if w in words]
        if len(target_hits) != 1:
            issues.append(f"{seq}: target hits {target_hits}")
        if len(words) != 4:
            issues.append(f"{seq}: expected 4 words, got {words}")
        if "nyajin" not in words or not lower_kuku.endswith(" nyajin."):
            issues.append(f"{seq}: missing final nyajin")
        if "nyajil" in lower_kuku:
            issues.append(f"{seq}: nonpast nyajil leakage")
        if len([w for w in ("yaluy", "yinyay") if w in words]) != 1:
            issues.append(f"{seq}: demonstrative problem {words}")
        expected_pronoun, expected_demo = FRAME_SPECS[(seq - 1) // 10]
        if words[0] != expected_pronoun:
            issues.append(f"{seq}: expected pronoun {expected_pronoun}, got {words[0]}")
        if words[2] != expected_demo:
            issues.append(f"{seq}: expected demonstrative {expected_demo}, got {words[2]}")
        if words[1] != TARGET_ORDER[(seq - 1) % 10]:
            issues.append(f"{seq}: target order mismatch {words[1]}")
        if words[3] != "nyajin":
            issues.append(f"{seq}: word 4 is not nyajin {words[3]}")
        if lower_kuku.rstrip(".") != " ".join(words):
            issues.append(f"{seq}: Kuku does not match words_used {words}")
        if not frame.startswith("r314_"):
            issues.append(f"{seq}: frame not r314 {frame}")
    return issues


def main() -> int:
    issues = scan_static()
    if issues:
        for issue in issues:
            print(issue)
        raise SystemExit(1)

    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    if db.execute("SELECT 1 FROM batches WHERE label=?", (LABEL,)).fetchone():
        raise SystemExit(f"{LABEL} already exists")
    collisions = []
    for _seq, _english, kuku, *_rest in ROWS:
        existing = 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!='rejected'
            """,
            (kuku,),
        ).fetchall()
        if existing:
            collisions.append((kuku, existing))
    if collisions:
        raise SystemExit(f"duplicate preflight failed: {collisions}")

    target_counts = count_words(db, TARGET_ORDER)
    support_counts = count_words(db, ["ngayu", "yundu", "nyulu", "bula", "jana", "yaluy", "yinyay", "nyajin"])
    verified_before, words_before = db.execute(
        """
        SELECT COUNT(*), SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()

    notes = (
        "VISIBLE TREE/PALM SINGULAR/THIRD-PERSON PAST PERCEPTION SWEEP AFTER RULE 313 (Rule 314). "
        "50 under-review rows over the ten Rule 310-313 tree/palm target heads with singular/third-person "
        "nominative pronouns and past nyajin: dulmbi umbrella palm, kakaji mangrove tree, mukukanka tree, murrkul "
        "tree, milbarkal tree, mirrbangku pencil cedar tree, mura tree, ngadil hickory tree, nyumbil coolibah tree, "
        "and wankar tree. SUPPORT: bare nominative ngayu, yundu, nyulu, bula, and jana, plus yaluy/yinyay and "
        "nyajin. Only bare visible object past perception/reference rows are opened; place names, timber, woomeras, "
        "shore/tide ecology, fruit, edible/food, leaching, poison, bloom timing, minya jalan, leech/fauna homographs, "
        "water-side ecology, flowers, seeds, necklaces, artefacts, target case, pronoun case, demonstrative case, "
        "compounds, nonpast/purposive/reduplicated perception drift, and support inflection remain closed."
    )
    cur = db.execute(
        "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
        (LABEL, "Rule 314 under review", "operator-guide-2026-07-10", notes, NOW),
    )
    batch_id = cur.lastrowid
    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used,
          evidence, status, confidence, rights_status, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (
                batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used,
                evidence, "under_review", confidence,
                "project_approved_synthetic_pending_elder_verification", "codex-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="source", event_type="source-readback", actor="codex", detail="Reread direct dictionary yaml entries for ten Rule 314 visible tree/palm targets; Patz singular/third-person pronoun, demonstrative, nyaji-ny, and past -ny evidence; and dictionary running-form nyajin examples before authoring Rule 314.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="visible-tree-palm-singular-third-past-scope", actor="codex", detail="Selected visible tree/palm singular/third-person past perception after Rule 313. The batch uses targets dulmbi, kakaji, mukukanka, murrkul, milbarkal, mirrbangku, mura, ngadil, nyumbil, and wankar with ngayu, yundu, nyulu, bula, jana, yaluy/yinyay, and dictionary-attested running-form nyajin. It opens no plant use, place-name, timber, woomera, shore/tide ecology, fruit, edible/food, leaching, poison, bloom, leech, necklace, artefact, case, compound, nonpast, purposive, reduplicated perception, or support-inflection semantics.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="coverage-audit", actor="codex", detail=f"Token-aware accepted/revised coverage before banking from words_used JSON: targets={target_counts}; support={support_counts}.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="duplicate-preflight", actor="codex", detail="Final 50 Rule 314 visible tree/palm singular/third-person past surfaces returned no accepted, revised, or under-review collisions.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="codex", detail="Static guard passed: 50 explicit hand-authored rows, one target each, bare singular/third-person nominative pronoun bands, bare yaluy/yinyay, final dictionary-form nyajin, no loans, no denied Kuku forms, no nyajil/nyajiny/segmented-form leakage, and no place/timber/woomera/fruit/bloom/leech/necklace/source-prose drift.", command="python3 -m py_compile batch_scripts/bank_356.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_356; print(bank_356.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_356.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="codex", detail=f"Banked 50 Rule 314 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_356.py", output_excerpt=f"banked batch-356: 50 rows under_review; verified_before={verified_before}; kuku_words_before={words_before}", artifact_path=PROCESS_LOG, created_at=NOW)
    db.commit()
    print("banked batch-356: 50 rows under_review")
    return 0


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