#!/usr/bin/env python3
"""Bank batch-316: Rule 274 fire-reference complementary past pronoun 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-316"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-316-fire-reference-complementary-past-pronoun-perception-after-rule273-process.md"

TARGET_HEADS = {
    "baya": "fire",
    "jimal": "fire stick",
    "jirramar": "small sticks",
    "kubu": "smoke",
    "kunjin": "fire",
    "miyilkura": "smouldering log",
    "ngalku": "bush fire",
    "ngaluri": "flames",
    "ngunjil": "charcoal",
    "wula": "flames",
}
PRONOUN_SUPPORT = {
    "ngayu": "1sg.NOM",
    "yundu": "2sg.NOM",
    "nyulu": "3sg.NOM",
    "bula": "3du.NOM",
    "ngana": "1pl.INC.NOM",
}
SUPPORT = set(PRONOUN_SUPPORT) | {"yaluy", "yinyay", "nyajin"}
DENY_KUKU = {
    "baya-wayu", "wayu", "waju", "dalngarri", "dama-murnil", "jakalambal", "jimal damal",
    "jimal-damal", "jimalili", "wulay", "kubu-kubu", "kunjirr", "ngalkun", "ngamar", "ngamba",
    "ngali", "ngaliny", "yubal", "nganjin", "yurra", "jana", "yulu", "nyajil", "nyaji-nka",
    "nyaji-nyaku", "nyaji-l-nyaji", "nyajiny", "nganya", "yununy", "yununiny", "nyunguny",
    "nyunguniny", "bulangan", "nganangan", "ngananiny", "ngananka", "ngananda", "nganandamuny",
    "ngananji", "ngananga", "ngaykunku", "yununku", "nyungunku", "ngaykundu", "yunundu",
    "nyungundu", "ngaykundumuny", "yunundumuny", "nyungundumuny", "ngaykunji", "yununji",
    "nyungunji", "ngayku", "yunu", "nyunju", "yinyangka", "yinyayngka", "yinyamba", "yinyamuny",
    "yalungku", "yaluyngku", "yaluymbu", "yaluyundu", "yalamuny", "yalanji",
}
DENY_ENGLISH = (
    "firewood", "light ", "lit ", "lighting", "start", "started", "starting", "make", "made",
    "making", "twirl", "drill", "collect", "collected", "gather", "gathered", "cook", "cooked",
    "cooking", "food", "damper", "leap", "leapt", "leaping", "shoot", "shooting", "spread",
    "spreading", "burn", "burned", "burning", "clear", "clearing", "grassfire", "danger", "warning",
    "smoke out", "source", "motion", "move", "moving", "warm", "urine", "pus", "body fluid",
    "ashes", "hot ashes", "hot coals", "coals", "matches", "motor", "loan", "story", "ritual",
    "ceremony", "purify", "mullet", "place", "tadpole", "my ", "your ", "his ", "her ", "their ",
    "possess", "owner", "case", "compound", "watch", "look", "listening", "hearing", "event",
    "use", "uses", "used",
)


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


EVIDENCE = {
    "baya": "Dictionary lines 1948-1962 give baya as noun 'fire', definitions flame/fire, baya wayu light a fire, and firewood. Rule 274 selects fire reference/perception only. Patz lines 2577-2586 and 2592-2603 source the bare nominative pronouns; lines 2838-2845 source yaluy/yinyay; lines 2568-2571 give nyaji-ny see-PAST; and lines 3043-3049 source nyaji-l 'see'.",
    "jimal": "Dictionary lines 9258-9268 give jimal as noun 'fire stick'. Nearby jimal damal and jimalili stay closed. Rule 274 selects fire-stick past perception/reference only.",
    "jirramar": "Dictionary lines 9863-9875 give jirramar as noun 'chips', translations chips/small sticks/twigs, with starting-fire prose. Rule 274 leaves starting-fire/kindling-use prose closed.",
    "kubu": "Dictionary lines 14707-14715 give kubu as noun 'smoke'. Nearby kubu-kubu tadpole stays closed.",
    "kunjin": "Dictionary lines 15880-15888 give kunjin as noun 'fire'. Nearby kunjirr purification/smoke prose stays closed.",
    "miyilkura": "Dictionary lines 19985-19993 give miyilkura as noun 'smouldering log'. Rule 274 opens no burning, cooking, warming, ash, or eye/miyil drift.",
    "ngalku": "Dictionary lines 21918-21926 give ngalku as noun 'bush fire'. Nearby ngalkun mullet stays closed.",
    "ngaluri": "Dictionary lines 22014-22025 give ngaluri as noun 'flames', with usage 'The flames leap up from the fire'. Rule 274 leaves leap-up event prose closed.",
    "ngunjil": "Dictionary lines 23679-23688 give ngunjil as noun 'charcoal', definition 'charcoal; hot coals or hot ashes'. Rule 274 selects charcoal only.",
    "wula": "Dictionary lines 27719-27729 give wula as noun 'flames', synonym dalngarri. Rule 274 leaves dalngarri synonymy and wulay verb drift closed.",
}

ROWS = [
    row(1, "I saw the fire here.", "Ngayu baya yaluy nyajin.", "ngayu baya yaluy nyajin | 1sg.NOM fire here see.PAST", "r274_1sg_fire_here_saw_baya", ["ngayu", "baya", "yaluy", "nyajin"], EVIDENCE["baya"]),
    row(2, "I saw the fire stick here.", "Ngayu jimal yaluy nyajin.", "ngayu jimal yaluy nyajin | 1sg.NOM fire.stick here see.PAST", "r274_1sg_fire_here_saw_jimal", ["ngayu", "jimal", "yaluy", "nyajin"], EVIDENCE["jimal"]),
    row(3, "I saw the small sticks here.", "Ngayu jirramar yaluy nyajin.", "ngayu jirramar yaluy nyajin | 1sg.NOM small.sticks here see.PAST", "r274_1sg_fire_here_saw_jirramar", ["ngayu", "jirramar", "yaluy", "nyajin"], EVIDENCE["jirramar"]),
    row(4, "I saw the smoke here.", "Ngayu kubu yaluy nyajin.", "ngayu kubu yaluy nyajin | 1sg.NOM smoke here see.PAST", "r274_1sg_fire_here_saw_kubu", ["ngayu", "kubu", "yaluy", "nyajin"], EVIDENCE["kubu"]),
    row(5, "I saw the fire here.", "Ngayu kunjin yaluy nyajin.", "ngayu kunjin yaluy nyajin | 1sg.NOM fire here see.PAST", "r274_1sg_fire_here_saw_kunjin", ["ngayu", "kunjin", "yaluy", "nyajin"], EVIDENCE["kunjin"]),
    row(6, "I saw the smouldering log here.", "Ngayu miyilkura yaluy nyajin.", "ngayu miyilkura yaluy nyajin | 1sg.NOM smouldering.log here see.PAST", "r274_1sg_fire_here_saw_miyilkura", ["ngayu", "miyilkura", "yaluy", "nyajin"], EVIDENCE["miyilkura"]),
    row(7, "I saw the bush fire here.", "Ngayu ngalku yaluy nyajin.", "ngayu ngalku yaluy nyajin | 1sg.NOM bush.fire here see.PAST", "r274_1sg_fire_here_saw_ngalku", ["ngayu", "ngalku", "yaluy", "nyajin"], EVIDENCE["ngalku"]),
    row(8, "I saw the flames here.", "Ngayu ngaluri yaluy nyajin.", "ngayu ngaluri yaluy nyajin | 1sg.NOM flames here see.PAST", "r274_1sg_fire_here_saw_ngaluri", ["ngayu", "ngaluri", "yaluy", "nyajin"], EVIDENCE["ngaluri"]),
    row(9, "I saw the charcoal here.", "Ngayu ngunjil yaluy nyajin.", "ngayu ngunjil yaluy nyajin | 1sg.NOM charcoal here see.PAST", "r274_1sg_fire_here_saw_ngunjil", ["ngayu", "ngunjil", "yaluy", "nyajin"], EVIDENCE["ngunjil"]),
    row(10, "I saw the flames here.", "Ngayu wula yaluy nyajin.", "ngayu wula yaluy nyajin | 1sg.NOM flames here see.PAST", "r274_1sg_fire_here_saw_wula", ["ngayu", "wula", "yaluy", "nyajin"], EVIDENCE["wula"]),
    row(11, "You saw the fire there.", "Yundu baya yinyay nyajin.", "yundu baya yinyay nyajin | 2sg.NOM fire there see.PAST", "r274_2sg_fire_there_saw_baya", ["yundu", "baya", "yinyay", "nyajin"], EVIDENCE["baya"]),
    row(12, "You saw the fire stick there.", "Yundu jimal yinyay nyajin.", "yundu jimal yinyay nyajin | 2sg.NOM fire.stick there see.PAST", "r274_2sg_fire_there_saw_jimal", ["yundu", "jimal", "yinyay", "nyajin"], EVIDENCE["jimal"]),
    row(13, "You saw the small sticks there.", "Yundu jirramar yinyay nyajin.", "yundu jirramar yinyay nyajin | 2sg.NOM small.sticks there see.PAST", "r274_2sg_fire_there_saw_jirramar", ["yundu", "jirramar", "yinyay", "nyajin"], EVIDENCE["jirramar"]),
    row(14, "You saw the smoke there.", "Yundu kubu yinyay nyajin.", "yundu kubu yinyay nyajin | 2sg.NOM smoke there see.PAST", "r274_2sg_fire_there_saw_kubu", ["yundu", "kubu", "yinyay", "nyajin"], EVIDENCE["kubu"]),
    row(15, "You saw the fire there.", "Yundu kunjin yinyay nyajin.", "yundu kunjin yinyay nyajin | 2sg.NOM fire there see.PAST", "r274_2sg_fire_there_saw_kunjin", ["yundu", "kunjin", "yinyay", "nyajin"], EVIDENCE["kunjin"]),
    row(16, "You saw the smouldering log there.", "Yundu miyilkura yinyay nyajin.", "yundu miyilkura yinyay nyajin | 2sg.NOM smouldering.log there see.PAST", "r274_2sg_fire_there_saw_miyilkura", ["yundu", "miyilkura", "yinyay", "nyajin"], EVIDENCE["miyilkura"]),
    row(17, "You saw the bush fire there.", "Yundu ngalku yinyay nyajin.", "yundu ngalku yinyay nyajin | 2sg.NOM bush.fire there see.PAST", "r274_2sg_fire_there_saw_ngalku", ["yundu", "ngalku", "yinyay", "nyajin"], EVIDENCE["ngalku"]),
    row(18, "You saw the flames there.", "Yundu ngaluri yinyay nyajin.", "yundu ngaluri yinyay nyajin | 2sg.NOM flames there see.PAST", "r274_2sg_fire_there_saw_ngaluri", ["yundu", "ngaluri", "yinyay", "nyajin"], EVIDENCE["ngaluri"]),
    row(19, "You saw the charcoal there.", "Yundu ngunjil yinyay nyajin.", "yundu ngunjil yinyay nyajin | 2sg.NOM charcoal there see.PAST", "r274_2sg_fire_there_saw_ngunjil", ["yundu", "ngunjil", "yinyay", "nyajin"], EVIDENCE["ngunjil"]),
    row(20, "You saw the flames there.", "Yundu wula yinyay nyajin.", "yundu wula yinyay nyajin | 2sg.NOM flames there see.PAST", "r274_2sg_fire_there_saw_wula", ["yundu", "wula", "yinyay", "nyajin"], EVIDENCE["wula"]),
    row(21, "He saw the fire here.", "Nyulu baya yaluy nyajin.", "nyulu baya yaluy nyajin | 3sg.NOM fire here see.PAST", "r274_3sg_fire_here_saw_baya", ["nyulu", "baya", "yaluy", "nyajin"], EVIDENCE["baya"]),
    row(22, "He saw the fire stick here.", "Nyulu jimal yaluy nyajin.", "nyulu jimal yaluy nyajin | 3sg.NOM fire.stick here see.PAST", "r274_3sg_fire_here_saw_jimal", ["nyulu", "jimal", "yaluy", "nyajin"], EVIDENCE["jimal"]),
    row(23, "He saw the small sticks here.", "Nyulu jirramar yaluy nyajin.", "nyulu jirramar yaluy nyajin | 3sg.NOM small.sticks here see.PAST", "r274_3sg_fire_here_saw_jirramar", ["nyulu", "jirramar", "yaluy", "nyajin"], EVIDENCE["jirramar"]),
    row(24, "He saw the smoke here.", "Nyulu kubu yaluy nyajin.", "nyulu kubu yaluy nyajin | 3sg.NOM smoke here see.PAST", "r274_3sg_fire_here_saw_kubu", ["nyulu", "kubu", "yaluy", "nyajin"], EVIDENCE["kubu"]),
    row(25, "He saw the fire here.", "Nyulu kunjin yaluy nyajin.", "nyulu kunjin yaluy nyajin | 3sg.NOM fire here see.PAST", "r274_3sg_fire_here_saw_kunjin", ["nyulu", "kunjin", "yaluy", "nyajin"], EVIDENCE["kunjin"]),
    row(26, "He saw the smouldering log here.", "Nyulu miyilkura yaluy nyajin.", "nyulu miyilkura yaluy nyajin | 3sg.NOM smouldering.log here see.PAST", "r274_3sg_fire_here_saw_miyilkura", ["nyulu", "miyilkura", "yaluy", "nyajin"], EVIDENCE["miyilkura"]),
    row(27, "He saw the bush fire here.", "Nyulu ngalku yaluy nyajin.", "nyulu ngalku yaluy nyajin | 3sg.NOM bush.fire here see.PAST", "r274_3sg_fire_here_saw_ngalku", ["nyulu", "ngalku", "yaluy", "nyajin"], EVIDENCE["ngalku"]),
    row(28, "He saw the flames here.", "Nyulu ngaluri yaluy nyajin.", "nyulu ngaluri yaluy nyajin | 3sg.NOM flames here see.PAST", "r274_3sg_fire_here_saw_ngaluri", ["nyulu", "ngaluri", "yaluy", "nyajin"], EVIDENCE["ngaluri"]),
    row(29, "He saw the charcoal here.", "Nyulu ngunjil yaluy nyajin.", "nyulu ngunjil yaluy nyajin | 3sg.NOM charcoal here see.PAST", "r274_3sg_fire_here_saw_ngunjil", ["nyulu", "ngunjil", "yaluy", "nyajin"], EVIDENCE["ngunjil"]),
    row(30, "He saw the flames here.", "Nyulu wula yaluy nyajin.", "nyulu wula yaluy nyajin | 3sg.NOM flames here see.PAST", "r274_3sg_fire_here_saw_wula", ["nyulu", "wula", "yaluy", "nyajin"], EVIDENCE["wula"]),
    row(31, "The two of them saw the fire there.", "Bula baya yinyay nyajin.", "bula baya yinyay nyajin | 3du.NOM fire there see.PAST", "r274_3du_fire_there_saw_baya", ["bula", "baya", "yinyay", "nyajin"], EVIDENCE["baya"]),
    row(32, "The two of them saw the fire stick there.", "Bula jimal yinyay nyajin.", "bula jimal yinyay nyajin | 3du.NOM fire.stick there see.PAST", "r274_3du_fire_there_saw_jimal", ["bula", "jimal", "yinyay", "nyajin"], EVIDENCE["jimal"]),
    row(33, "The two of them saw the small sticks there.", "Bula jirramar yinyay nyajin.", "bula jirramar yinyay nyajin | 3du.NOM small.sticks there see.PAST", "r274_3du_fire_there_saw_jirramar", ["bula", "jirramar", "yinyay", "nyajin"], EVIDENCE["jirramar"]),
    row(34, "The two of them saw the smoke there.", "Bula kubu yinyay nyajin.", "bula kubu yinyay nyajin | 3du.NOM smoke there see.PAST", "r274_3du_fire_there_saw_kubu", ["bula", "kubu", "yinyay", "nyajin"], EVIDENCE["kubu"]),
    row(35, "The two of them saw the fire there.", "Bula kunjin yinyay nyajin.", "bula kunjin yinyay nyajin | 3du.NOM fire there see.PAST", "r274_3du_fire_there_saw_kunjin", ["bula", "kunjin", "yinyay", "nyajin"], EVIDENCE["kunjin"]),
    row(36, "The two of them saw the smouldering log there.", "Bula miyilkura yinyay nyajin.", "bula miyilkura yinyay nyajin | 3du.NOM smouldering.log there see.PAST", "r274_3du_fire_there_saw_miyilkura", ["bula", "miyilkura", "yinyay", "nyajin"], EVIDENCE["miyilkura"]),
    row(37, "The two of them saw the bush fire there.", "Bula ngalku yinyay nyajin.", "bula ngalku yinyay nyajin | 3du.NOM bush.fire there see.PAST", "r274_3du_fire_there_saw_ngalku", ["bula", "ngalku", "yinyay", "nyajin"], EVIDENCE["ngalku"]),
    row(38, "The two of them saw the flames there.", "Bula ngaluri yinyay nyajin.", "bula ngaluri yinyay nyajin | 3du.NOM flames there see.PAST", "r274_3du_fire_there_saw_ngaluri", ["bula", "ngaluri", "yinyay", "nyajin"], EVIDENCE["ngaluri"]),
    row(39, "The two of them saw the charcoal there.", "Bula ngunjil yinyay nyajin.", "bula ngunjil yinyay nyajin | 3du.NOM charcoal there see.PAST", "r274_3du_fire_there_saw_ngunjil", ["bula", "ngunjil", "yinyay", "nyajin"], EVIDENCE["ngunjil"]),
    row(40, "The two of them saw the flames there.", "Bula wula yinyay nyajin.", "bula wula yinyay nyajin | 3du.NOM flames there see.PAST", "r274_3du_fire_there_saw_wula", ["bula", "wula", "yinyay", "nyajin"], EVIDENCE["wula"]),
    row(41, "We saw the fire there.", "Ngana baya yinyay nyajin.", "ngana baya yinyay nyajin | 1pl.INC.NOM fire there see.PAST", "r274_1pl_incl_fire_there_saw_baya", ["ngana", "baya", "yinyay", "nyajin"], EVIDENCE["baya"]),
    row(42, "We saw the fire stick there.", "Ngana jimal yinyay nyajin.", "ngana jimal yinyay nyajin | 1pl.INC.NOM fire.stick there see.PAST", "r274_1pl_incl_fire_there_saw_jimal", ["ngana", "jimal", "yinyay", "nyajin"], EVIDENCE["jimal"]),
    row(43, "We saw the small sticks there.", "Ngana jirramar yinyay nyajin.", "ngana jirramar yinyay nyajin | 1pl.INC.NOM small.sticks there see.PAST", "r274_1pl_incl_fire_there_saw_jirramar", ["ngana", "jirramar", "yinyay", "nyajin"], EVIDENCE["jirramar"]),
    row(44, "We saw the smoke there.", "Ngana kubu yinyay nyajin.", "ngana kubu yinyay nyajin | 1pl.INC.NOM smoke there see.PAST", "r274_1pl_incl_fire_there_saw_kubu", ["ngana", "kubu", "yinyay", "nyajin"], EVIDENCE["kubu"]),
    row(45, "We saw the fire there.", "Ngana kunjin yinyay nyajin.", "ngana kunjin yinyay nyajin | 1pl.INC.NOM fire there see.PAST", "r274_1pl_incl_fire_there_saw_kunjin", ["ngana", "kunjin", "yinyay", "nyajin"], EVIDENCE["kunjin"]),
    row(46, "We saw the smouldering log there.", "Ngana miyilkura yinyay nyajin.", "ngana miyilkura yinyay nyajin | 1pl.INC.NOM smouldering.log there see.PAST", "r274_1pl_incl_fire_there_saw_miyilkura", ["ngana", "miyilkura", "yinyay", "nyajin"], EVIDENCE["miyilkura"]),
    row(47, "We saw the bush fire there.", "Ngana ngalku yinyay nyajin.", "ngana ngalku yinyay nyajin | 1pl.INC.NOM bush.fire there see.PAST", "r274_1pl_incl_fire_there_saw_ngalku", ["ngana", "ngalku", "yinyay", "nyajin"], EVIDENCE["ngalku"]),
    row(48, "We saw the flames there.", "Ngana ngaluri yinyay nyajin.", "ngana ngaluri yinyay nyajin | 1pl.INC.NOM flames there see.PAST", "r274_1pl_incl_fire_there_saw_ngaluri", ["ngana", "ngaluri", "yinyay", "nyajin"], EVIDENCE["ngaluri"]),
    row(49, "We saw the charcoal there.", "Ngana ngunjil yinyay nyajin.", "ngana ngunjil yinyay nyajin | 1pl.INC.NOM charcoal there see.PAST", "r274_1pl_incl_fire_there_saw_ngunjil", ["ngana", "ngunjil", "yinyay", "nyajin"], EVIDENCE["ngunjil"]),
    row(50, "We saw the flames there.", "Ngana wula yinyay nyajin.", "ngana wula yinyay nyajin | 1pl.INC.NOM flames there see.PAST", "r274_1pl_incl_fire_there_saw_wula", ["ngana", "wula", "yinyay", "nyajin"], EVIDENCE["wula"]),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", 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: set[str] = set()
    for expected, data in enumerate(ROWS, 1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = 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")
        if low in seen:
            issues.append(f"{label}: duplicate surface inside batch")
        seen.add(low)
        if not frame.startswith("r274_"):
            issues.append(f"{label}: frame must start with r274_")
        if " | " not in analysis or "see.PAST" not in analysis:
            issues.append(f"{label}: analysis missing gloss separator or see.PAST")
        if json.loads(loans_used):
            issues.append(f"{label}: loans_used must be empty")
        denied = [bad for bad in DENY_KUKU if has_token(low, bad)]
        if denied:
            issues.append(f"{label}: denied Kuku token(s) present: {denied}")
        targets = [head for head in TARGET_HEADS if has_token(low, head)]
        if len(targets) != 1:
            issues.append(f"{label}: expected one 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 re.search(rf"(?<![a-z-]){re.escape(head)}-[a-z]+", low):
                issues.append(f"{label}: target head {head} has forbidden suffix/compound")
        pronouns = [pronoun for pronoun in PRONOUN_SUPPORT if has_token(low, pronoun)]
        if len(pronouns) != 1:
            issues.append(f"{label}: expected one selected bare nominative pronoun, found {pronouns}")
        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 " saw " not in f" {english_low} ":
            issues.append(f"{label}: English must use past 'saw'")
        if "nyajin" not in words or not low.endswith(" nyajin."):
            issues.append(f"{label}: row must end with nyajin")
        if 1 <= seq <= 10 and (not low.startswith("ngayu ") or not low.endswith(" yaluy nyajin.")):
            issues.append(f"{label}: rows 1-10 require Ngayu TARGET yaluy nyajin")
        if 11 <= seq <= 20 and (not low.startswith("yundu ") or not low.endswith(" yinyay nyajin.")):
            issues.append(f"{label}: rows 11-20 require Yundu TARGET yinyay nyajin")
        if 21 <= seq <= 30 and (not low.startswith("nyulu ") or not low.endswith(" yaluy nyajin.")):
            issues.append(f"{label}: rows 21-30 require Nyulu TARGET yaluy nyajin")
        if 31 <= seq <= 40 and (not low.startswith("bula ") or not low.endswith(" yinyay nyajin.")):
            issues.append(f"{label}: rows 31-40 require Bula TARGET yinyay nyajin")
        if 41 <= seq <= 50 and (not low.startswith("ngana ") or not low.endswith(" yinyay nyajin.")):
            issues.append(f"{label}: rows 41-50 require Ngana TARGET yinyay nyajin")
        if len(low.split()) != 4:
            issues.append(f"{label}: expected four Kuku tokens")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied fire action/use 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 lessons WHERE batch_id=?", (batch_id,))
        db.execute("DELETE FROM sentences WHERE batch_id=?", (batch_id,))
        db.execute("UPDATE batches SET notes=?, created_at=? WHERE id=?", ("rebanked under_review", NOW, batch_id))
    else:
        db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 274 draft", "operator-guide-2026-07-09", "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}: {kuku} -> {found}")
    if collisions:
        raise SystemExit("collision scan failed:\n" + "\n".join(collisions))

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, created_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, 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="Rule 274 source pass checked dictionary lines for the ten fire-reference targets and Patz pronoun, demonstrative, and nyaji-ny see-PAST lines before banking.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="planning",
        event_type="debt-sweep-scope",
        actor="claude-main",
        detail="Selected Rule 274 fire-reference complementary past pronoun perception sweep after Rule 273: ten checked fire-reference labels in five zero-collision bare-pronoun past-perception bands using ngayu, yundu, nyulu, bula, and ngana.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="coverage-audit",
        actor="claude-main",
        detail="Coverage after Rule 273: baya 483, jimal 58, jirramar 30, kubu 86, kunjin 36, miyilkura 30, ngalku 30, ngaluri 30, ngunjil 93, wula 84; support ngayu 1341, yundu 1201, nyulu 1816, bula 244, ngana 990, yaluy 2704, yinyay 2948, nyajin 1452.",
        command="sqlite3 synthetic.db token-aware coverage query",
        output_excerpt="Targets: baya 483, jimal 58, jirramar 30, kubu 86, kunjin 36, miyilkura 30, ngalku 30, ngaluri 30, ngunjil 93, wula 84. Support: ngayu 1341, yundu 1201, nyulu 1816, bula 244, ngana 990, yaluy 2704, yinyay 2948, nyajin 1452.",
        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 the 50 final Rule 274 fire-reference complementary past perception surfaces found no accepted, revised, or under-review collisions.",
        command="sqlite3 synthetic.db planned-surface duplicate query",
        output_excerpt="0 rows returned.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="bank_316.py static guards passed: 50 rows, r274 frame prefix, one checked fire-reference target per row, exactly one selected bare nominative pronoun per row, expected complementary past here/there bands, nyajin see.PAST only, no denied fire action/use/homograph/source-prose/case/perception-compound tokens, and no loans.",
        command="python3 -m py_compile batch_scripts/bank_316.py; import bank_316; bank_316.scan_static()",
        output_excerpt="issues 0",
        artifact_path="batch_scripts/bank_316.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="bank",
        event_type="bank-success",
        actor="claude-main",
        detail="Inserted 50 explicit Batch 316 / Rule 274 rows as under_review.",
        command="python3 batch_scripts/bank_316.py",
        output_excerpt="banked batch-316: 50 rows under_review",
        artifact_path="synthetic.db",
        created_at=NOW,
    )
    db.commit()
    print(f"banked {LABEL}: 50 rows under_review")
    return 0


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