#!/usr/bin/env python3
"""Bank batch-357: Rule 315 low-coverage visible tree singular/third 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-357"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-357-low-coverage-visible-tree-singular-third-nonpast-perception-after-rule314-process.md"

TARGET_EVIDENCE = {
    "miyilabu": "Dictionary yaml lines 19850-19873 give miyilabu as noun 'tree' / 'mangrove', with separate prose about poisonous sap, blindness, and an association with miyil 'eye'. Rule 315 selects visible miyilabu mangrove-tree reference only and leaves sap, poison, blindness, fish-stupefying, eye etymology, use, and ecology rows closed.",
    "ngalkarran": "Dictionary yaml lines 21896-21917 give ngalkarran as noun 'tree', with source prose about an edible red seed or apple-like fruit ripening August-October. Rule 315 selects visible ngalkarran-tree reference only and leaves seed, colour, fruit, edibility, apple comparison, ripening, month, season, and food rows closed.",
    "wada": "Dictionary yaml lines 25015-25036 give wada as noun 'tree' / 'small tree', with source prose about an edible white seed or apple-sized fruit ripening August-October. Rule 315 selects visible wada-tree reference only and leaves size, seed, colour, fruit, edibility, apple comparison, ripening, month, season, and food rows closed.",
    "wangku": "Dictionary yaml lines 26023-26034 give wangku as noun 'small tree' or 'wood goanna'. Rule 315 selects visible wangku-tree reference only and leaves the wood-goanna/fauna reading, size predicates, habitat, and event rows closed.",
    "yinkunji": "Dictionary yaml lines 30302-30325 give yinkunji as noun 'tree' / 'fig tree', with source prose about edible long black fruit ripening in the wet season. Rule 315 selects visible yinkunji fig-tree reference only and leaves fruit, shape, colour, edibility, wet-season ripening, food, and ecology rows closed.",
    "yurrunji": "Dictionary yaml lines 31080-31101 give yurrunji as noun 'tree' / 'dead finish', with country distribution, Main camp, Romeo, love, rejection, and solitary-tree story prose. Rule 315 selects visible yurrunji-tree reference only and leaves exonym, place, country distribution, personification, love/rejection, solitary, and story rows closed.",
    "jajikal": "Dictionary yaml lines 7027-7069 give jajikal place-name/Bloomfield senses and a distinct noun 'screw palm' / 'pandanus palm', also associated with lower camp at Ayton. Rule 315 selects visible jajikal screw-palm reference only and leaves Bloomfield, river-mouth, Ayton, lower-camp, abundance, place-name, leaf, weaving, and use rows closed.",
    "jalnji": "Dictionary yaml lines 7591-7611 give jalnji as noun 'poison nut tree' / 'nut tree', with source prose about human inedibility and non-poisonous gum used for spears. Rule 315 selects visible jalnji-tree reference only and leaves poison, nut/food, edibility, gum, spear, material, and use rows closed.",
    "jinjay": "Dictionary yaml lines 9539-9559 give jinjay as noun 'poison nut tree' / 'tree', with source prose about roasting, poisonous smoke/bark/sap, and a cooked-wattle-bark skin cure. Rule 315 selects visible jinjay-tree reference only and leaves nut/fruit, roasting, smoke, poison, bark, sap, water, cure, skin, food, medicine, and use rows closed.",
    "kurubarr": "Dictionary yaml lines 16709-16720 give kurubarr as noun 'mangrove', with source prose about a long round seed. Rule 315 selects visible kurubarr-mangrove reference only and leaves seed, shape, fruit, shore/tide ecology, and use rows closed.",
}

SUPPORT_EVIDENCE = (
    "Living grammar pronoun table lines 2577-2586 sources bare nominatives ngayu, yundu, nyulu, bula, and jana, "
    "including the note that nyulu is more common than yulu; demonstrative lines 2834-2847 source Yalanji yaluy "
    "'here' and yinyay 'there'; lines 3043-3049 give nyaji-l as nonpast 'see', and lines 3149-3151 define nonpast "
    "present/future function. Grammar lines 4256-4265 license nominative pronoun A with bare absolutive O, including "
    "sensory perception. Dictionary lines 24282-24296 independently attest running-form nyajil as an l-conjugation "
    "general perception verb including 'see'. Rule 315 uses only the visual sense and bare support forms."
)

TARGET_ORDER = ["miyilabu", "ngalkarran", "wada", "wangku", "yinkunji", "yurrunji", "jajikal", "jalnji", "jinjay", "kurubarr"]
TARGET_LABELS = {
    "miyilabu": "miyilabu mangrove tree",
    "ngalkarran": "ngalkarran tree",
    "wada": "wada tree",
    "wangku": "wangku tree",
    "yinkunji": "yinkunji fig tree",
    "yurrunji": "yurrunji tree",
    "jajikal": "jajikal screw palm",
    "jalnji": "jalnji tree",
    "jinjay": "jinjay tree",
    "kurubarr": "kurubarr mangrove",
}
FRAME_SPECS = [
    ("ngayu", "yinyay", "I see", "there"),
    ("yundu", "yaluy", "You see", "here"),
    ("nyulu", "yinyay", "He sees", "there"),
    ("bula", "yaluy", "The two of them see", "here"),
    ("jana", "yinyay", "They see", "there"),
]

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",
    "dulmbi", "kakaji", "mukukanka", "murrkul", "milbarkal", "mirrbangku", "mura", "ngadil",
    "nyumbil", "wankar", "jarrabi", "kalbawurr", "jina-jina", "kuray-kuray", "mangkurru",
    "yalungku", "yaluyngku", "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajin", "nyajiny", "nyaji-ny", "nyaji-nka", "nyaji-l-nyaji", "milka", "baykal", "jalngkay",
}
DENY_ENGLISH = (
    "place", "bloomfield", "ayton", "camp", "river", "mouth", "north", "poison", "poisonous", "sap",
    "blind", "blindness", "fish", "eye", "edible", "seed", "red", "white", "apple", "ripe", "ripening",
    "august", "october", "fruit", "wood", "goanna", "wet", "season", "country", "main", "romeo", "love",
    "rejected", "alone", "solitary", "story", "gum", "spear", "material", "roast", "roasting", "smoke",
    "bark", "cure", "skin", "food", "medicine", "water", "timber", "woomera", "leaf", "weaving", "use",
    "used", "using", "ecology", "long", "round",
)


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 lower(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 see the miyilabu mangrove tree there.", "Ngayu miyilabu yinyay nyajil.", "ngayu miyilabu yinyay nyajil | 1sg.NOM miyilabu.mangrove.tree there see.NPST", "r315_1sg_there_low_tree_see_miyilabu", ["ngayu", "miyilabu", "yinyay", "nyajil"]),
    row(2, "I see the ngalkarran tree there.", "Ngayu ngalkarran yinyay nyajil.", "ngayu ngalkarran yinyay nyajil | 1sg.NOM ngalkarran.tree there see.NPST", "r315_1sg_there_low_tree_see_ngalkarran", ["ngayu", "ngalkarran", "yinyay", "nyajil"]),
    row(3, "I see the wada tree there.", "Ngayu wada yinyay nyajil.", "ngayu wada yinyay nyajil | 1sg.NOM wada.tree there see.NPST", "r315_1sg_there_low_tree_see_wada", ["ngayu", "wada", "yinyay", "nyajil"]),
    row(4, "I see the wangku tree there.", "Ngayu wangku yinyay nyajil.", "ngayu wangku yinyay nyajil | 1sg.NOM wangku.tree there see.NPST", "r315_1sg_there_low_tree_see_wangku", ["ngayu", "wangku", "yinyay", "nyajil"]),
    row(5, "I see the yinkunji fig tree there.", "Ngayu yinkunji yinyay nyajil.", "ngayu yinkunji yinyay nyajil | 1sg.NOM yinkunji.fig.tree there see.NPST", "r315_1sg_there_low_tree_see_yinkunji", ["ngayu", "yinkunji", "yinyay", "nyajil"]),
    row(6, "I see the yurrunji tree there.", "Ngayu yurrunji yinyay nyajil.", "ngayu yurrunji yinyay nyajil | 1sg.NOM yurrunji.tree there see.NPST", "r315_1sg_there_low_tree_see_yurrunji", ["ngayu", "yurrunji", "yinyay", "nyajil"]),
    row(7, "I see the jajikal screw palm there.", "Ngayu jajikal yinyay nyajil.", "ngayu jajikal yinyay nyajil | 1sg.NOM jajikal.screw.palm there see.NPST", "r315_1sg_there_low_tree_see_jajikal", ["ngayu", "jajikal", "yinyay", "nyajil"]),
    row(8, "I see the jalnji tree there.", "Ngayu jalnji yinyay nyajil.", "ngayu jalnji yinyay nyajil | 1sg.NOM jalnji.tree there see.NPST", "r315_1sg_there_low_tree_see_jalnji", ["ngayu", "jalnji", "yinyay", "nyajil"]),
    row(9, "I see the jinjay tree there.", "Ngayu jinjay yinyay nyajil.", "ngayu jinjay yinyay nyajil | 1sg.NOM jinjay.tree there see.NPST", "r315_1sg_there_low_tree_see_jinjay", ["ngayu", "jinjay", "yinyay", "nyajil"]),
    row(10, "I see the kurubarr mangrove there.", "Ngayu kurubarr yinyay nyajil.", "ngayu kurubarr yinyay nyajil | 1sg.NOM kurubarr.mangrove there see.NPST", "r315_1sg_there_low_tree_see_kurubarr", ["ngayu", "kurubarr", "yinyay", "nyajil"]),
    row(11, "You see the miyilabu mangrove tree here.", "Yundu miyilabu yaluy nyajil.", "yundu miyilabu yaluy nyajil | 2sg.NOM miyilabu.mangrove.tree here see.NPST", "r315_2sg_here_low_tree_see_miyilabu", ["yundu", "miyilabu", "yaluy", "nyajil"]),
    row(12, "You see the ngalkarran tree here.", "Yundu ngalkarran yaluy nyajil.", "yundu ngalkarran yaluy nyajil | 2sg.NOM ngalkarran.tree here see.NPST", "r315_2sg_here_low_tree_see_ngalkarran", ["yundu", "ngalkarran", "yaluy", "nyajil"]),
    row(13, "You see the wada tree here.", "Yundu wada yaluy nyajil.", "yundu wada yaluy nyajil | 2sg.NOM wada.tree here see.NPST", "r315_2sg_here_low_tree_see_wada", ["yundu", "wada", "yaluy", "nyajil"]),
    row(14, "You see the wangku tree here.", "Yundu wangku yaluy nyajil.", "yundu wangku yaluy nyajil | 2sg.NOM wangku.tree here see.NPST", "r315_2sg_here_low_tree_see_wangku", ["yundu", "wangku", "yaluy", "nyajil"]),
    row(15, "You see the yinkunji fig tree here.", "Yundu yinkunji yaluy nyajil.", "yundu yinkunji yaluy nyajil | 2sg.NOM yinkunji.fig.tree here see.NPST", "r315_2sg_here_low_tree_see_yinkunji", ["yundu", "yinkunji", "yaluy", "nyajil"]),
    row(16, "You see the yurrunji tree here.", "Yundu yurrunji yaluy nyajil.", "yundu yurrunji yaluy nyajil | 2sg.NOM yurrunji.tree here see.NPST", "r315_2sg_here_low_tree_see_yurrunji", ["yundu", "yurrunji", "yaluy", "nyajil"]),
    row(17, "You see the jajikal screw palm here.", "Yundu jajikal yaluy nyajil.", "yundu jajikal yaluy nyajil | 2sg.NOM jajikal.screw.palm here see.NPST", "r315_2sg_here_low_tree_see_jajikal", ["yundu", "jajikal", "yaluy", "nyajil"]),
    row(18, "You see the jalnji tree here.", "Yundu jalnji yaluy nyajil.", "yundu jalnji yaluy nyajil | 2sg.NOM jalnji.tree here see.NPST", "r315_2sg_here_low_tree_see_jalnji", ["yundu", "jalnji", "yaluy", "nyajil"]),
    row(19, "You see the jinjay tree here.", "Yundu jinjay yaluy nyajil.", "yundu jinjay yaluy nyajil | 2sg.NOM jinjay.tree here see.NPST", "r315_2sg_here_low_tree_see_jinjay", ["yundu", "jinjay", "yaluy", "nyajil"]),
    row(20, "You see the kurubarr mangrove here.", "Yundu kurubarr yaluy nyajil.", "yundu kurubarr yaluy nyajil | 2sg.NOM kurubarr.mangrove here see.NPST", "r315_2sg_here_low_tree_see_kurubarr", ["yundu", "kurubarr", "yaluy", "nyajil"]),
    row(21, "He sees the miyilabu mangrove tree there.", "Nyulu miyilabu yinyay nyajil.", "nyulu miyilabu yinyay nyajil | 3sg.NOM miyilabu.mangrove.tree there see.NPST", "r315_3sg_there_low_tree_see_miyilabu", ["nyulu", "miyilabu", "yinyay", "nyajil"]),
    row(22, "He sees the ngalkarran tree there.", "Nyulu ngalkarran yinyay nyajil.", "nyulu ngalkarran yinyay nyajil | 3sg.NOM ngalkarran.tree there see.NPST", "r315_3sg_there_low_tree_see_ngalkarran", ["nyulu", "ngalkarran", "yinyay", "nyajil"]),
    row(23, "He sees the wada tree there.", "Nyulu wada yinyay nyajil.", "nyulu wada yinyay nyajil | 3sg.NOM wada.tree there see.NPST", "r315_3sg_there_low_tree_see_wada", ["nyulu", "wada", "yinyay", "nyajil"]),
    row(24, "He sees the wangku tree there.", "Nyulu wangku yinyay nyajil.", "nyulu wangku yinyay nyajil | 3sg.NOM wangku.tree there see.NPST", "r315_3sg_there_low_tree_see_wangku", ["nyulu", "wangku", "yinyay", "nyajil"]),
    row(25, "He sees the yinkunji fig tree there.", "Nyulu yinkunji yinyay nyajil.", "nyulu yinkunji yinyay nyajil | 3sg.NOM yinkunji.fig.tree there see.NPST", "r315_3sg_there_low_tree_see_yinkunji", ["nyulu", "yinkunji", "yinyay", "nyajil"]),
    row(26, "He sees the yurrunji tree there.", "Nyulu yurrunji yinyay nyajil.", "nyulu yurrunji yinyay nyajil | 3sg.NOM yurrunji.tree there see.NPST", "r315_3sg_there_low_tree_see_yurrunji", ["nyulu", "yurrunji", "yinyay", "nyajil"]),
    row(27, "He sees the jajikal screw palm there.", "Nyulu jajikal yinyay nyajil.", "nyulu jajikal yinyay nyajil | 3sg.NOM jajikal.screw.palm there see.NPST", "r315_3sg_there_low_tree_see_jajikal", ["nyulu", "jajikal", "yinyay", "nyajil"]),
    row(28, "He sees the jalnji tree there.", "Nyulu jalnji yinyay nyajil.", "nyulu jalnji yinyay nyajil | 3sg.NOM jalnji.tree there see.NPST", "r315_3sg_there_low_tree_see_jalnji", ["nyulu", "jalnji", "yinyay", "nyajil"]),
    row(29, "He sees the jinjay tree there.", "Nyulu jinjay yinyay nyajil.", "nyulu jinjay yinyay nyajil | 3sg.NOM jinjay.tree there see.NPST", "r315_3sg_there_low_tree_see_jinjay", ["nyulu", "jinjay", "yinyay", "nyajil"]),
    row(30, "He sees the kurubarr mangrove there.", "Nyulu kurubarr yinyay nyajil.", "nyulu kurubarr yinyay nyajil | 3sg.NOM kurubarr.mangrove there see.NPST", "r315_3sg_there_low_tree_see_kurubarr", ["nyulu", "kurubarr", "yinyay", "nyajil"]),
    row(31, "The two of them see the miyilabu mangrove tree here.", "Bula miyilabu yaluy nyajil.", "bula miyilabu yaluy nyajil | 3du.NOM miyilabu.mangrove.tree here see.NPST", "r315_3du_here_low_tree_see_miyilabu", ["bula", "miyilabu", "yaluy", "nyajil"]),
    row(32, "The two of them see the ngalkarran tree here.", "Bula ngalkarran yaluy nyajil.", "bula ngalkarran yaluy nyajil | 3du.NOM ngalkarran.tree here see.NPST", "r315_3du_here_low_tree_see_ngalkarran", ["bula", "ngalkarran", "yaluy", "nyajil"]),
    row(33, "The two of them see the wada tree here.", "Bula wada yaluy nyajil.", "bula wada yaluy nyajil | 3du.NOM wada.tree here see.NPST", "r315_3du_here_low_tree_see_wada", ["bula", "wada", "yaluy", "nyajil"]),
    row(34, "The two of them see the wangku tree here.", "Bula wangku yaluy nyajil.", "bula wangku yaluy nyajil | 3du.NOM wangku.tree here see.NPST", "r315_3du_here_low_tree_see_wangku", ["bula", "wangku", "yaluy", "nyajil"]),
    row(35, "The two of them see the yinkunji fig tree here.", "Bula yinkunji yaluy nyajil.", "bula yinkunji yaluy nyajil | 3du.NOM yinkunji.fig.tree here see.NPST", "r315_3du_here_low_tree_see_yinkunji", ["bula", "yinkunji", "yaluy", "nyajil"]),
    row(36, "The two of them see the yurrunji tree here.", "Bula yurrunji yaluy nyajil.", "bula yurrunji yaluy nyajil | 3du.NOM yurrunji.tree here see.NPST", "r315_3du_here_low_tree_see_yurrunji", ["bula", "yurrunji", "yaluy", "nyajil"]),
    row(37, "The two of them see the jajikal screw palm here.", "Bula jajikal yaluy nyajil.", "bula jajikal yaluy nyajil | 3du.NOM jajikal.screw.palm here see.NPST", "r315_3du_here_low_tree_see_jajikal", ["bula", "jajikal", "yaluy", "nyajil"]),
    row(38, "The two of them see the jalnji tree here.", "Bula jalnji yaluy nyajil.", "bula jalnji yaluy nyajil | 3du.NOM jalnji.tree here see.NPST", "r315_3du_here_low_tree_see_jalnji", ["bula", "jalnji", "yaluy", "nyajil"]),
    row(39, "The two of them see the jinjay tree here.", "Bula jinjay yaluy nyajil.", "bula jinjay yaluy nyajil | 3du.NOM jinjay.tree here see.NPST", "r315_3du_here_low_tree_see_jinjay", ["bula", "jinjay", "yaluy", "nyajil"]),
    row(40, "The two of them see the kurubarr mangrove here.", "Bula kurubarr yaluy nyajil.", "bula kurubarr yaluy nyajil | 3du.NOM kurubarr.mangrove here see.NPST", "r315_3du_here_low_tree_see_kurubarr", ["bula", "kurubarr", "yaluy", "nyajil"]),
    row(41, "They see the miyilabu mangrove tree there.", "Jana miyilabu yinyay nyajil.", "jana miyilabu yinyay nyajil | 3pl.NOM miyilabu.mangrove.tree there see.NPST", "r315_3pl_there_low_tree_see_miyilabu", ["jana", "miyilabu", "yinyay", "nyajil"]),
    row(42, "They see the ngalkarran tree there.", "Jana ngalkarran yinyay nyajil.", "jana ngalkarran yinyay nyajil | 3pl.NOM ngalkarran.tree there see.NPST", "r315_3pl_there_low_tree_see_ngalkarran", ["jana", "ngalkarran", "yinyay", "nyajil"]),
    row(43, "They see the wada tree there.", "Jana wada yinyay nyajil.", "jana wada yinyay nyajil | 3pl.NOM wada.tree there see.NPST", "r315_3pl_there_low_tree_see_wada", ["jana", "wada", "yinyay", "nyajil"]),
    row(44, "They see the wangku tree there.", "Jana wangku yinyay nyajil.", "jana wangku yinyay nyajil | 3pl.NOM wangku.tree there see.NPST", "r315_3pl_there_low_tree_see_wangku", ["jana", "wangku", "yinyay", "nyajil"]),
    row(45, "They see the yinkunji fig tree there.", "Jana yinkunji yinyay nyajil.", "jana yinkunji yinyay nyajil | 3pl.NOM yinkunji.fig.tree there see.NPST", "r315_3pl_there_low_tree_see_yinkunji", ["jana", "yinkunji", "yinyay", "nyajil"]),
    row(46, "They see the yurrunji tree there.", "Jana yurrunji yinyay nyajil.", "jana yurrunji yinyay nyajil | 3pl.NOM yurrunji.tree there see.NPST", "r315_3pl_there_low_tree_see_yurrunji", ["jana", "yurrunji", "yinyay", "nyajil"]),
    row(47, "They see the jajikal screw palm there.", "Jana jajikal yinyay nyajil.", "jana jajikal yinyay nyajil | 3pl.NOM jajikal.screw.palm there see.NPST", "r315_3pl_there_low_tree_see_jajikal", ["jana", "jajikal", "yinyay", "nyajil"]),
    row(48, "They see the jalnji tree there.", "Jana jalnji yinyay nyajil.", "jana jalnji yinyay nyajil | 3pl.NOM jalnji.tree there see.NPST", "r315_3pl_there_low_tree_see_jalnji", ["jana", "jalnji", "yinyay", "nyajil"]),
    row(49, "They see the jinjay tree there.", "Jana jinjay yinyay nyajil.", "jana jinjay yinyay nyajil | 3pl.NOM jinjay.tree there see.NPST", "r315_3pl_there_low_tree_see_jinjay", ["jana", "jinjay", "yinyay", "nyajil"]),
    row(50, "They see the kurubarr mangrove there.", "Jana kurubarr yinyay nyajil.", "jana kurubarr yinyay nyajil | 3pl.NOM kurubarr.mangrove there see.NPST", "r315_3pl_there_low_tree_see_kurubarr", ["jana", "kurubarr", "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()
        band = (seq - 1) // 10
        target = TARGET_ORDER[(seq - 1) % 10]
        pronoun, demo, english_prefix, english_location = FRAME_SPECS[band]
        expected_kuku = f"{pronoun.capitalize()} {target} {demo} nyajil."
        expected_english = f"{english_prefix} the {TARGET_LABELS[target]} {english_location}."
        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)}\b", lower_english)]
        if denied_english:
            issues.append(f"{seq}: denied English drift {denied_english}")
        if kuku != expected_kuku:
            issues.append(f"{seq}: Kuku mismatch expected {expected_kuku!r}, got {kuku!r}")
        if english != expected_english:
            issues.append(f"{seq}: English mismatch expected {expected_english!r}, got {english!r}")
        if words != [pronoun, target, demo, "nyajil"]:
            issues.append(f"{seq}: words mismatch {words}")
        if lower_kuku.rstrip(".") != " ".join(words):
            issues.append(f"{seq}: Kuku does not match words_used {words}")
        if not frame.startswith("r315_"):
            issues.append(f"{seq}: frame not r315 {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", "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 = (
        "LOW-COVERAGE VISIBLE TREE/PALM/MANGROVE SINGULAR/THIRD-PERSON NONPAST PERCEPTION SWEEP AFTER RULE 314 "
        "(Rule 315). 50 under-review rows over six zero-use and four one-use direct-dictionary target heads: "
        "miyilabu mangrove tree, ngalkarran tree, wada tree, wangku tree, yinkunji fig tree, yurrunji tree, jajikal "
        "screw palm, jalnji tree, jinjay tree, and kurubarr mangrove. SUPPORT: bare nominative ngayu, yundu, nyulu, "
        "bula, and jana, Yalanji yaluy/yinyay, and dictionary-attested nonpast nyajil. Only bare visible tree "
        "reference/perception is opened; place names, fruit/seed/food, poison/sap/blindness, wood-goanna homograph, "
        "country/story/personification, timber/woomera/spear/gum/material use, case, compounds, past/purposive/"
        "reduplicated perception, and support inflection remain closed."
    )
    cur = db.execute(
        "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
        (LABEL, "Rule 315 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 all ten Rule 315 low-coverage visible tree/palm/mangrove targets, dictionary nyajil, and Patz pronoun, demonstrative, nonpast, and pronoun-A/bare-O evidence before authoring Rule 315.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="low-coverage-visible-tree-singular-third-nonpast-scope", actor="codex", detail="Selected six zero-use and four one-use direct-dictionary tree/palm/mangrove heads for bare singular/third-person nonpast visual perception. Explicitly closed place-name, poison/sap/blindness, fruit/seed/food, wood-goanna, country/story/personification, timber/woomera/spear/gum, material-use, case, compound, past/purposive/reduplicated perception, and 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 315 low-coverage visible tree/palm/mangrove singular/third-person 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="codex", detail="Static guard passed: 50 explicit hand-authored rows, exact per-sequence Kuku and English contracts, one selected target each, bare nominative pronoun bands, bare yaluy/yinyay, final nyajil, no loans, no denied Kuku forms, and no source-prose/polysemy drift.", command="python3 -m py_compile batch_scripts/bank_357.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_357; print(bank_357.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_357.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="codex", detail=f"Banked 50 Rule 315 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_357.py", output_excerpt=f"banked batch-357: 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-357: 50 rows under_review")
    return 0


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