#!/usr/bin/env python3
"""Bank batch-354: Rule 312 visible tree/palm non-singular nonpast 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-354"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-354-visible-tree-palm-nonsingular-nonpast-perception-after-rule311-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 312 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 312 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 312 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 312 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 312 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 312 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 312 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 312 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 312 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 312 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 ngali, ngaliny, yubal, yurra, and ngana "
    "with non-nominative case forms separated in the same table; grammar lines 2678-2686 discuss first-person "
    "inclusive/exclusive and second-person non-singular forms; demonstrative lines 2834-2845 source yaluy 'here' "
    "and yinyay 'there'; grammar lines 3043-3049 give nyaji-l as the non-past form of 'see'. Rule 312 uses only "
    "bare support forms and corpus-conventional nyajil as the surface of nyaji-l."
)

TARGET_ORDER = ["dulmbi", "kakaji", "mukukanka", "murrkul", "milbarkal", "mirrbangku", "mura", "ngadil", "nyumbil", "wankar"]
FRAME_SPECS = [
    ("ngali", "yinyay"),
    ("ngaliny", "yaluy"),
    ("yubal", "yinyay"),
    ("yurra", "yaluy"),
    ("ngana", "yinyay"),
]

DENY_KUKU = {
    "ngayu", "yundu", "nyulu", "bula", "jana", "yulu", "iana", "nganjin",
    "ngalingan", "ngalinyan", "yubalan", "bulangan", "ngalininy", "ngalinyiny", "yubaliny",
    "ngalinka", "ngalinyanka", "yubalanka", "ngalinda", "ngalinyanda", "yubalanda",
    "ngalindamuny", "ngalinyandamuny", "yubalandamuny", "ngalinji", "ngalinyanji", "yubalanji",
    "ngalinga", "ngalinyanga", "yubalanga", "nganjinan", "nganangan", "yurrangan",
    "nganjininy", "ngananiny", "yurraniny", "nganjinanka", "ngananka", "yurranka",
    "nganjinanda", "ngananda", "yurranda", "nganjinandamuny", "nganandamuny", "yurrandamuny",
    "nganjinanji", "ngananji", "yurranji", "nganjinanga", "ngananga", "yurranga",
    "bujabay", "jingajalka", "jirimandi", "julbal", "jungka", "karranda", "karrandal",
    "kawarr", "marril", "ngurrkul", "jinajina", "kuraykuray", "luku",
    "yalungku", "yaluyngku", "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajin", "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, "We two, not you, see the dulmbi umbrella palm there.", "Ngali dulmbi yinyay nyajil.", "ngali dulmbi yinyay nyajil | 1du.EXCL.NOM dulmbi.umbrella.palm there see.NPST", "r312_1du_excl_there_tree_see_dulmbi", ["ngali", "dulmbi", "yinyay", "nyajil"]),
    row(2, "We two, not you, see the kakaji mangrove tree there.", "Ngali kakaji yinyay nyajil.", "ngali kakaji yinyay nyajil | 1du.EXCL.NOM kakaji.mangrove.tree there see.NPST", "r312_1du_excl_there_tree_see_kakaji", ["ngali", "kakaji", "yinyay", "nyajil"]),
    row(3, "We two, not you, see the mukukanka tree there.", "Ngali mukukanka yinyay nyajil.", "ngali mukukanka yinyay nyajil | 1du.EXCL.NOM mukukanka.tree there see.NPST", "r312_1du_excl_there_tree_see_mukukanka", ["ngali", "mukukanka", "yinyay", "nyajil"]),
    row(4, "We two, not you, see the murrkul tree there.", "Ngali murrkul yinyay nyajil.", "ngali murrkul yinyay nyajil | 1du.EXCL.NOM murrkul.tree there see.NPST", "r312_1du_excl_there_tree_see_murrkul", ["ngali", "murrkul", "yinyay", "nyajil"]),
    row(5, "We two, not you, see the milbarkal tree there.", "Ngali milbarkal yinyay nyajil.", "ngali milbarkal yinyay nyajil | 1du.EXCL.NOM milbarkal.tree there see.NPST", "r312_1du_excl_there_tree_see_milbarkal", ["ngali", "milbarkal", "yinyay", "nyajil"]),
    row(6, "We two, not you, see the mirrbangku pencil cedar tree there.", "Ngali mirrbangku yinyay nyajil.", "ngali mirrbangku yinyay nyajil | 1du.EXCL.NOM mirrbangku.pencil.cedar.tree there see.NPST", "r312_1du_excl_there_tree_see_mirrbangku", ["ngali", "mirrbangku", "yinyay", "nyajil"]),
    row(7, "We two, not you, see the mura tree there.", "Ngali mura yinyay nyajil.", "ngali mura yinyay nyajil | 1du.EXCL.NOM mura.tree there see.NPST", "r312_1du_excl_there_tree_see_mura", ["ngali", "mura", "yinyay", "nyajil"]),
    row(8, "We two, not you, see the ngadil hickory tree there.", "Ngali ngadil yinyay nyajil.", "ngali ngadil yinyay nyajil | 1du.EXCL.NOM ngadil.hickory.tree there see.NPST", "r312_1du_excl_there_tree_see_ngadil", ["ngali", "ngadil", "yinyay", "nyajil"]),
    row(9, "We two, not you, see the nyumbil coolibah tree there.", "Ngali nyumbil yinyay nyajil.", "ngali nyumbil yinyay nyajil | 1du.EXCL.NOM nyumbil.coolibah.tree there see.NPST", "r312_1du_excl_there_tree_see_nyumbil", ["ngali", "nyumbil", "yinyay", "nyajil"]),
    row(10, "We two, not you, see the wankar tree there.", "Ngali wankar yinyay nyajil.", "ngali wankar yinyay nyajil | 1du.EXCL.NOM wankar.tree there see.NPST", "r312_1du_excl_there_tree_see_wankar", ["ngali", "wankar", "yinyay", "nyajil"]),
    row(11, "You and I see the dulmbi umbrella palm here.", "Ngaliny dulmbi yaluy nyajil.", "ngaliny dulmbi yaluy nyajil | 1du.INCL.NOM dulmbi.umbrella.palm here see.NPST", "r312_1du_incl_here_tree_see_dulmbi", ["ngaliny", "dulmbi", "yaluy", "nyajil"]),
    row(12, "You and I see the kakaji mangrove tree here.", "Ngaliny kakaji yaluy nyajil.", "ngaliny kakaji yaluy nyajil | 1du.INCL.NOM kakaji.mangrove.tree here see.NPST", "r312_1du_incl_here_tree_see_kakaji", ["ngaliny", "kakaji", "yaluy", "nyajil"]),
    row(13, "You and I see the mukukanka tree here.", "Ngaliny mukukanka yaluy nyajil.", "ngaliny mukukanka yaluy nyajil | 1du.INCL.NOM mukukanka.tree here see.NPST", "r312_1du_incl_here_tree_see_mukukanka", ["ngaliny", "mukukanka", "yaluy", "nyajil"]),
    row(14, "You and I see the murrkul tree here.", "Ngaliny murrkul yaluy nyajil.", "ngaliny murrkul yaluy nyajil | 1du.INCL.NOM murrkul.tree here see.NPST", "r312_1du_incl_here_tree_see_murrkul", ["ngaliny", "murrkul", "yaluy", "nyajil"]),
    row(15, "You and I see the milbarkal tree here.", "Ngaliny milbarkal yaluy nyajil.", "ngaliny milbarkal yaluy nyajil | 1du.INCL.NOM milbarkal.tree here see.NPST", "r312_1du_incl_here_tree_see_milbarkal", ["ngaliny", "milbarkal", "yaluy", "nyajil"]),
    row(16, "You and I see the mirrbangku pencil cedar tree here.", "Ngaliny mirrbangku yaluy nyajil.", "ngaliny mirrbangku yaluy nyajil | 1du.INCL.NOM mirrbangku.pencil.cedar.tree here see.NPST", "r312_1du_incl_here_tree_see_mirrbangku", ["ngaliny", "mirrbangku", "yaluy", "nyajil"]),
    row(17, "You and I see the mura tree here.", "Ngaliny mura yaluy nyajil.", "ngaliny mura yaluy nyajil | 1du.INCL.NOM mura.tree here see.NPST", "r312_1du_incl_here_tree_see_mura", ["ngaliny", "mura", "yaluy", "nyajil"]),
    row(18, "You and I see the ngadil hickory tree here.", "Ngaliny ngadil yaluy nyajil.", "ngaliny ngadil yaluy nyajil | 1du.INCL.NOM ngadil.hickory.tree here see.NPST", "r312_1du_incl_here_tree_see_ngadil", ["ngaliny", "ngadil", "yaluy", "nyajil"]),
    row(19, "You and I see the nyumbil coolibah tree here.", "Ngaliny nyumbil yaluy nyajil.", "ngaliny nyumbil yaluy nyajil | 1du.INCL.NOM nyumbil.coolibah.tree here see.NPST", "r312_1du_incl_here_tree_see_nyumbil", ["ngaliny", "nyumbil", "yaluy", "nyajil"]),
    row(20, "You and I see the wankar tree here.", "Ngaliny wankar yaluy nyajil.", "ngaliny wankar yaluy nyajil | 1du.INCL.NOM wankar.tree here see.NPST", "r312_1du_incl_here_tree_see_wankar", ["ngaliny", "wankar", "yaluy", "nyajil"]),
    row(21, "You two see the dulmbi umbrella palm there.", "Yubal dulmbi yinyay nyajil.", "yubal dulmbi yinyay nyajil | 2du.NOM dulmbi.umbrella.palm there see.NPST", "r312_2du_there_tree_see_dulmbi", ["yubal", "dulmbi", "yinyay", "nyajil"]),
    row(22, "You two see the kakaji mangrove tree there.", "Yubal kakaji yinyay nyajil.", "yubal kakaji yinyay nyajil | 2du.NOM kakaji.mangrove.tree there see.NPST", "r312_2du_there_tree_see_kakaji", ["yubal", "kakaji", "yinyay", "nyajil"]),
    row(23, "You two see the mukukanka tree there.", "Yubal mukukanka yinyay nyajil.", "yubal mukukanka yinyay nyajil | 2du.NOM mukukanka.tree there see.NPST", "r312_2du_there_tree_see_mukukanka", ["yubal", "mukukanka", "yinyay", "nyajil"]),
    row(24, "You two see the murrkul tree there.", "Yubal murrkul yinyay nyajil.", "yubal murrkul yinyay nyajil | 2du.NOM murrkul.tree there see.NPST", "r312_2du_there_tree_see_murrkul", ["yubal", "murrkul", "yinyay", "nyajil"]),
    row(25, "You two see the milbarkal tree there.", "Yubal milbarkal yinyay nyajil.", "yubal milbarkal yinyay nyajil | 2du.NOM milbarkal.tree there see.NPST", "r312_2du_there_tree_see_milbarkal", ["yubal", "milbarkal", "yinyay", "nyajil"]),
    row(26, "You two see the mirrbangku pencil cedar tree there.", "Yubal mirrbangku yinyay nyajil.", "yubal mirrbangku yinyay nyajil | 2du.NOM mirrbangku.pencil.cedar.tree there see.NPST", "r312_2du_there_tree_see_mirrbangku", ["yubal", "mirrbangku", "yinyay", "nyajil"]),
    row(27, "You two see the mura tree there.", "Yubal mura yinyay nyajil.", "yubal mura yinyay nyajil | 2du.NOM mura.tree there see.NPST", "r312_2du_there_tree_see_mura", ["yubal", "mura", "yinyay", "nyajil"]),
    row(28, "You two see the ngadil hickory tree there.", "Yubal ngadil yinyay nyajil.", "yubal ngadil yinyay nyajil | 2du.NOM ngadil.hickory.tree there see.NPST", "r312_2du_there_tree_see_ngadil", ["yubal", "ngadil", "yinyay", "nyajil"]),
    row(29, "You two see the nyumbil coolibah tree there.", "Yubal nyumbil yinyay nyajil.", "yubal nyumbil yinyay nyajil | 2du.NOM nyumbil.coolibah.tree there see.NPST", "r312_2du_there_tree_see_nyumbil", ["yubal", "nyumbil", "yinyay", "nyajil"]),
    row(30, "You two see the wankar tree there.", "Yubal wankar yinyay nyajil.", "yubal wankar yinyay nyajil | 2du.NOM wankar.tree there see.NPST", "r312_2du_there_tree_see_wankar", ["yubal", "wankar", "yinyay", "nyajil"]),
    row(31, "You all see the dulmbi umbrella palm here.", "Yurra dulmbi yaluy nyajil.", "yurra dulmbi yaluy nyajil | 2pl.NOM dulmbi.umbrella.palm here see.NPST", "r312_2pl_here_tree_see_dulmbi", ["yurra", "dulmbi", "yaluy", "nyajil"]),
    row(32, "You all see the kakaji mangrove tree here.", "Yurra kakaji yaluy nyajil.", "yurra kakaji yaluy nyajil | 2pl.NOM kakaji.mangrove.tree here see.NPST", "r312_2pl_here_tree_see_kakaji", ["yurra", "kakaji", "yaluy", "nyajil"]),
    row(33, "You all see the mukukanka tree here.", "Yurra mukukanka yaluy nyajil.", "yurra mukukanka yaluy nyajil | 2pl.NOM mukukanka.tree here see.NPST", "r312_2pl_here_tree_see_mukukanka", ["yurra", "mukukanka", "yaluy", "nyajil"]),
    row(34, "You all see the murrkul tree here.", "Yurra murrkul yaluy nyajil.", "yurra murrkul yaluy nyajil | 2pl.NOM murrkul.tree here see.NPST", "r312_2pl_here_tree_see_murrkul", ["yurra", "murrkul", "yaluy", "nyajil"]),
    row(35, "You all see the milbarkal tree here.", "Yurra milbarkal yaluy nyajil.", "yurra milbarkal yaluy nyajil | 2pl.NOM milbarkal.tree here see.NPST", "r312_2pl_here_tree_see_milbarkal", ["yurra", "milbarkal", "yaluy", "nyajil"]),
    row(36, "You all see the mirrbangku pencil cedar tree here.", "Yurra mirrbangku yaluy nyajil.", "yurra mirrbangku yaluy nyajil | 2pl.NOM mirrbangku.pencil.cedar.tree here see.NPST", "r312_2pl_here_tree_see_mirrbangku", ["yurra", "mirrbangku", "yaluy", "nyajil"]),
    row(37, "You all see the mura tree here.", "Yurra mura yaluy nyajil.", "yurra mura yaluy nyajil | 2pl.NOM mura.tree here see.NPST", "r312_2pl_here_tree_see_mura", ["yurra", "mura", "yaluy", "nyajil"]),
    row(38, "You all see the ngadil hickory tree here.", "Yurra ngadil yaluy nyajil.", "yurra ngadil yaluy nyajil | 2pl.NOM ngadil.hickory.tree here see.NPST", "r312_2pl_here_tree_see_ngadil", ["yurra", "ngadil", "yaluy", "nyajil"]),
    row(39, "You all see the nyumbil coolibah tree here.", "Yurra nyumbil yaluy nyajil.", "yurra nyumbil yaluy nyajil | 2pl.NOM nyumbil.coolibah.tree here see.NPST", "r312_2pl_here_tree_see_nyumbil", ["yurra", "nyumbil", "yaluy", "nyajil"]),
    row(40, "You all see the wankar tree here.", "Yurra wankar yaluy nyajil.", "yurra wankar yaluy nyajil | 2pl.NOM wankar.tree here see.NPST", "r312_2pl_here_tree_see_wankar", ["yurra", "wankar", "yaluy", "nyajil"]),
    row(41, "We see the dulmbi umbrella palm there.", "Ngana dulmbi yinyay nyajil.", "ngana dulmbi yinyay nyajil | 1pl.INCL.NOM dulmbi.umbrella.palm there see.NPST", "r312_1pl_incl_there_tree_see_dulmbi", ["ngana", "dulmbi", "yinyay", "nyajil"]),
    row(42, "We see the kakaji mangrove tree there.", "Ngana kakaji yinyay nyajil.", "ngana kakaji yinyay nyajil | 1pl.INCL.NOM kakaji.mangrove.tree there see.NPST", "r312_1pl_incl_there_tree_see_kakaji", ["ngana", "kakaji", "yinyay", "nyajil"]),
    row(43, "We see the mukukanka tree there.", "Ngana mukukanka yinyay nyajil.", "ngana mukukanka yinyay nyajil | 1pl.INCL.NOM mukukanka.tree there see.NPST", "r312_1pl_incl_there_tree_see_mukukanka", ["ngana", "mukukanka", "yinyay", "nyajil"]),
    row(44, "We see the murrkul tree there.", "Ngana murrkul yinyay nyajil.", "ngana murrkul yinyay nyajil | 1pl.INCL.NOM murrkul.tree there see.NPST", "r312_1pl_incl_there_tree_see_murrkul", ["ngana", "murrkul", "yinyay", "nyajil"]),
    row(45, "We see the milbarkal tree there.", "Ngana milbarkal yinyay nyajil.", "ngana milbarkal yinyay nyajil | 1pl.INCL.NOM milbarkal.tree there see.NPST", "r312_1pl_incl_there_tree_see_milbarkal", ["ngana", "milbarkal", "yinyay", "nyajil"]),
    row(46, "We see the mirrbangku pencil cedar tree there.", "Ngana mirrbangku yinyay nyajil.", "ngana mirrbangku yinyay nyajil | 1pl.INCL.NOM mirrbangku.pencil.cedar.tree there see.NPST", "r312_1pl_incl_there_tree_see_mirrbangku", ["ngana", "mirrbangku", "yinyay", "nyajil"]),
    row(47, "We see the mura tree there.", "Ngana mura yinyay nyajil.", "ngana mura yinyay nyajil | 1pl.INCL.NOM mura.tree there see.NPST", "r312_1pl_incl_there_tree_see_mura", ["ngana", "mura", "yinyay", "nyajil"]),
    row(48, "We see the ngadil hickory tree there.", "Ngana ngadil yinyay nyajil.", "ngana ngadil yinyay nyajil | 1pl.INCL.NOM ngadil.hickory.tree there see.NPST", "r312_1pl_incl_there_tree_see_ngadil", ["ngana", "ngadil", "yinyay", "nyajil"]),
    row(49, "We see the nyumbil coolibah tree there.", "Ngana nyumbil yinyay nyajil.", "ngana nyumbil yinyay nyajil | 1pl.INCL.NOM nyumbil.coolibah.tree there see.NPST", "r312_1pl_incl_there_tree_see_nyumbil", ["ngana", "nyumbil", "yinyay", "nyajil"]),
    row(50, "We see the wankar tree there.", "Ngana wankar yinyay nyajil.", "ngana wankar yinyay nyajil | 1pl.INCL.NOM wankar.tree there see.NPST", "r312_1pl_incl_there_tree_see_wankar", ["ngana", "wankar", "yinyay", "nyajil"]),
]


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 " see " not in f" {lower_english} " and " sees " not in f" {lower_english} ":
            issues.append(f"{seq}: English is not nonpast see/sees")
        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 "nyajil" not in words or not lower_kuku.endswith(" nyajil."):
            issues.append(f"{seq}: missing final nyajil")
        if "nyajin" in lower_kuku:
            issues.append(f"{seq}: past nyajin 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] != "nyajil":
            issues.append(f"{seq}: word 4 is not nyajil {words[3]}")
        if lower_kuku.rstrip(".") != " ".join(words):
            issues.append(f"{seq}: Kuku does not match words_used {words}")
        if not frame.startswith("r312_"):
            issues.append(f"{seq}: frame not r312 {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, ["ngali", "ngaliny", "yubal", "yurra", "ngana", "yaluy", "yinyay", "nyajil"])
    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 NON-SINGULAR NONPAST PERCEPTION SWEEP AFTER RULE 311 (Rule 312). "
        "50 under-review rows over the ten Rule 310-311 tree/palm target heads with non-singular nominative "
        "pronouns: 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 ngali, ngaliny, yubal, yurra, and ngana, plus yaluy/yinyay and nyajil. Only bare "
        "visible object nonpast 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, past/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 312 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", "claude", 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="claude-main", detail="Reread direct dictionary yaml entries for ten Rule 312 visible tree/palm targets and living grammar non-singular pronoun, demonstrative, and nyaji-l/nyajil nonpast support before authoring Rule 312.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="visible-tree-palm-nonsingular-nonpast-scope", actor="claude-main", detail="Selected visible tree/palm non-singular nonpast perception after Rule 311. The batch uses targets dulmbi, kakaji, mukukanka, murrkul, milbarkal, mirrbangku, mura, ngadil, nyumbil, and wankar with ngali, ngaliny, yubal, yurra, ngana, yaluy/yinyay, and nyajil. It opens no plant use, place-name, timber, woomera, shore/tide ecology, fruit, edible/food, leaching, poison, bloom, leech, necklace, artefact, case, compound, past, 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="claude-main", 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="claude-main", detail="Final 50 Rule 312 visible tree/palm non-singular nonpast 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="claude-main", detail="Static guard passed: 50 explicit hand-authored rows, one target each, bare non-singular nominative pronoun bands, bare yaluy/yinyay, final nyajil, no loans, no denied Kuku forms, no past nyajin leakage, and no place/timber/woomera/fruit/bloom/leech/necklace/source-prose drift.", command="python3 -m py_compile batch_scripts/bank_354.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_354; print(bank_354.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_354.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 312 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_354.py", output_excerpt=f"banked batch-354: 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-354: 50 rows under_review")
    return 0


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