#!/usr/bin/env python3
"""Bank batch-326: Rule 284 non-singular visible sky/celestial 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-326"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-326-visible-sky-celestial-nonsingular-nonpast-pronoun-perception-after-rule283-process.md"

TARGET_HEADS = {
    "balbay": "lightning",
    "binyu": "shooting star",
    "dawar": "star",
    "jiri": "sky",
    "kaba": "rain",
    "kija": "moon",
    "wungar": "sun",
    "kurrinkurrin": "mackerel sky",
    "kurrubijal": "morning star",
    "yiril": "rainbow",
}
TARGET_ORDER = [
    "balbay", "binyu", "dawar", "jiri", "kaba", "kija", "wungar", "kurrinkurrin", "kurrubijal", "yiril",
]
SUPPORT = {"ngali", "ngaliny", "yubal", "yurra", "jana", "yaluy", "yinyay", "nyajil"}
DENY_KUKU = {
    "ngurrban", "dawarr", "jiri bajaku", "jiri-warra", "jiri-wuran", "kababina", "kaba-kada",
    "kijandaku", "jarunga-kija", "juru-kija", "jurungu-kija", "yangkija", "wungar dakal",
    "wungar daray", "wungar jalamal", "wungar jarra-jarra", "wungar wandil-wandil",
    "wungar wangkar-wangkar", "wungar-iji", "wungariji", "yirilngka", "ngalingan", "ngalinyan",
    "yubalan", "yurrangan", "janangan", "ngalininy", "ngalinyiny", "yubaliny", "yurraniny",
    "jananiny", "ngalinka", "ngalinyanka", "yubalanka", "yurranka", "jananka", "ngalinda",
    "ngalinyanda", "yubalanda", "yurranda", "jananda", "ngalinji", "ngalinyanji", "yubalanji",
    "yurranji", "jananji", "ngalinga", "ngalinyanga", "yubalanga", "yurranga", "jananga",
    "nyajin", "nyaji-ny", "nyaji-nka", "nyaji-l-nyaji", "yinyangka", "yinyayngka", "yinyamba",
    "yinyamuny", "yalungku", "yaluyngku", "yaluymbu", "yaluyundu", "yalamuny",
}
DENY_ENGLISH = (
    "month", "roaring meg", "creation", "place", "spirit", "omen", "death", "dead", "die", "died",
    "strike", "struck", "weather event", "falling rain", "rain falls", "rainbird", "thunder", "wind",
    "storm", "hot season", "season", "sunrise", "sunset", "midday", "time", "heaven", "sky mob",
    "cloudless", "fine day", "story", "snake", "water hole", "country", "belong", "use", "used",
    "route", "travel", "danger", "illness", "body", "case", "compound", "event",
)


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 = {
    "balbay": "Dictionary lines 900-911 give balbay as noun 'lightning' and include lightning-strike example prose. Rule 284 selects visible lightning only and leaves strike/event rows closed. Patz lines 2577-2586 and 2592-2603 source bare non-singular nominative pronouns; lines 2674-2686 source non-singular contrasts; lines 2838-2845 source yaluy/yinyay; and lines 3043-3049 source nyaji-l 'see'.",
    "binyu": "Dictionary lines 3063-3074 give binyu as noun 'shooting star' and record death-spirit/death-omen belief prose. Rule 284 selects visible shooting-star reference only.",
    "dawar": "Dictionary lines 5374-5382 give dawar as noun 'star'. Rule 284 selects visible star reference only and leaves dawarr 'straw hat' closed.",
    "jiri": "Dictionary lines 9720-9730 give jiri as noun 'sky/heaven'. Rule 284 selects visible sky reference only and leaves heaven, fine-day, sky-mob, and place-name compounds closed.",
    "kaba": "Dictionary lines 11671-11679 give kaba as noun 'rain'. Rule 284 selects visible rain reference only and leaves falling/coming/weather-event rows closed.",
    "kija": "Dictionary lines 14143-14155 give kija as noun 'moon' with Roaring Meg Falls / moon-story place sense. Rule 284 selects visible moon reference only and leaves month/place/story rows closed.",
    "wungar": "Dictionary lines 28081-28089 give wungar as noun 'sun'. Rule 284 selects visible sun reference only and leaves sunrise, sunset, midday, hot-season, and sun-locative compounds closed.",
    "kurrinkurrin": "Dictionary lines 16406-16419 give kurrinkurrin as noun 'mackerel sky' and mark it as reduplicated. Rule 284 treats it as a lexicalized noun only, not productive reduplication.",
    "kurrubijal": "Dictionary lines 16557-16567 give kurrubijal as noun 'morning star', Venus as morning star. Rule 284 selects visible morning-star reference only.",
    "yiril": "Dictionary lines 30419-30427 give yiril as noun 'rainbow'. Rule 284 selects visible rainbow reference only and leaves story/snake/water-hole extensions closed.",
}

ROWS = [
    row(1, "We two (not you) see the lightning there.", "Ngali balbay yinyay nyajil.", "ngali balbay yinyay nyajil | 1du.EXCL.NOM lightning there see.NPST", "r284_1du_excl_sky_celestial_there_see_balbay", ["ngali", "balbay", "yinyay", "nyajil"], EVIDENCE["balbay"]),
    row(2, "We two (not you) see the shooting star there.", "Ngali binyu yinyay nyajil.", "ngali binyu yinyay nyajil | 1du.EXCL.NOM shooting.star there see.NPST", "r284_1du_excl_sky_celestial_there_see_binyu", ["ngali", "binyu", "yinyay", "nyajil"], EVIDENCE["binyu"]),
    row(3, "We two (not you) see the star there.", "Ngali dawar yinyay nyajil.", "ngali dawar yinyay nyajil | 1du.EXCL.NOM star there see.NPST", "r284_1du_excl_sky_celestial_there_see_dawar", ["ngali", "dawar", "yinyay", "nyajil"], EVIDENCE["dawar"]),
    row(4, "We two (not you) see the sky there.", "Ngali jiri yinyay nyajil.", "ngali jiri yinyay nyajil | 1du.EXCL.NOM sky there see.NPST", "r284_1du_excl_sky_celestial_there_see_jiri", ["ngali", "jiri", "yinyay", "nyajil"], EVIDENCE["jiri"]),
    row(5, "We two (not you) see the rain there.", "Ngali kaba yinyay nyajil.", "ngali kaba yinyay nyajil | 1du.EXCL.NOM rain there see.NPST", "r284_1du_excl_sky_celestial_there_see_kaba", ["ngali", "kaba", "yinyay", "nyajil"], EVIDENCE["kaba"]),
    row(6, "We two (not you) see the moon there.", "Ngali kija yinyay nyajil.", "ngali kija yinyay nyajil | 1du.EXCL.NOM moon there see.NPST", "r284_1du_excl_sky_celestial_there_see_kija", ["ngali", "kija", "yinyay", "nyajil"], EVIDENCE["kija"]),
    row(7, "We two (not you) see the sun there.", "Ngali wungar yinyay nyajil.", "ngali wungar yinyay nyajil | 1du.EXCL.NOM sun there see.NPST", "r284_1du_excl_sky_celestial_there_see_wungar", ["ngali", "wungar", "yinyay", "nyajil"], EVIDENCE["wungar"]),
    row(8, "We two (not you) see the mackerel sky there.", "Ngali kurrinkurrin yinyay nyajil.", "ngali kurrinkurrin yinyay nyajil | 1du.EXCL.NOM mackerel.sky there see.NPST", "r284_1du_excl_sky_celestial_there_see_kurrinkurrin", ["ngali", "kurrinkurrin", "yinyay", "nyajil"], EVIDENCE["kurrinkurrin"]),
    row(9, "We two (not you) see the morning star there.", "Ngali kurrubijal yinyay nyajil.", "ngali kurrubijal yinyay nyajil | 1du.EXCL.NOM morning.star there see.NPST", "r284_1du_excl_sky_celestial_there_see_kurrubijal", ["ngali", "kurrubijal", "yinyay", "nyajil"], EVIDENCE["kurrubijal"]),
    row(10, "We two (not you) see the rainbow there.", "Ngali yiril yinyay nyajil.", "ngali yiril yinyay nyajil | 1du.EXCL.NOM rainbow there see.NPST", "r284_1du_excl_sky_celestial_there_see_yiril", ["ngali", "yiril", "yinyay", "nyajil"], EVIDENCE["yiril"]),
    row(11, "You and I see the lightning here.", "Ngaliny balbay yaluy nyajil.", "ngaliny balbay yaluy nyajil | 1du.INCL.NOM lightning here see.NPST", "r284_1du_incl_sky_celestial_here_see_balbay", ["ngaliny", "balbay", "yaluy", "nyajil"], EVIDENCE["balbay"]),
    row(12, "You and I see the shooting star here.", "Ngaliny binyu yaluy nyajil.", "ngaliny binyu yaluy nyajil | 1du.INCL.NOM shooting.star here see.NPST", "r284_1du_incl_sky_celestial_here_see_binyu", ["ngaliny", "binyu", "yaluy", "nyajil"], EVIDENCE["binyu"]),
    row(13, "You and I see the star here.", "Ngaliny dawar yaluy nyajil.", "ngaliny dawar yaluy nyajil | 1du.INCL.NOM star here see.NPST", "r284_1du_incl_sky_celestial_here_see_dawar", ["ngaliny", "dawar", "yaluy", "nyajil"], EVIDENCE["dawar"]),
    row(14, "You and I see the sky here.", "Ngaliny jiri yaluy nyajil.", "ngaliny jiri yaluy nyajil | 1du.INCL.NOM sky here see.NPST", "r284_1du_incl_sky_celestial_here_see_jiri", ["ngaliny", "jiri", "yaluy", "nyajil"], EVIDENCE["jiri"]),
    row(15, "You and I see the rain here.", "Ngaliny kaba yaluy nyajil.", "ngaliny kaba yaluy nyajil | 1du.INCL.NOM rain here see.NPST", "r284_1du_incl_sky_celestial_here_see_kaba", ["ngaliny", "kaba", "yaluy", "nyajil"], EVIDENCE["kaba"]),
    row(16, "You and I see the moon here.", "Ngaliny kija yaluy nyajil.", "ngaliny kija yaluy nyajil | 1du.INCL.NOM moon here see.NPST", "r284_1du_incl_sky_celestial_here_see_kija", ["ngaliny", "kija", "yaluy", "nyajil"], EVIDENCE["kija"]),
    row(17, "You and I see the sun here.", "Ngaliny wungar yaluy nyajil.", "ngaliny wungar yaluy nyajil | 1du.INCL.NOM sun here see.NPST", "r284_1du_incl_sky_celestial_here_see_wungar", ["ngaliny", "wungar", "yaluy", "nyajil"], EVIDENCE["wungar"]),
    row(18, "You and I see the mackerel sky here.", "Ngaliny kurrinkurrin yaluy nyajil.", "ngaliny kurrinkurrin yaluy nyajil | 1du.INCL.NOM mackerel.sky here see.NPST", "r284_1du_incl_sky_celestial_here_see_kurrinkurrin", ["ngaliny", "kurrinkurrin", "yaluy", "nyajil"], EVIDENCE["kurrinkurrin"]),
    row(19, "You and I see the morning star here.", "Ngaliny kurrubijal yaluy nyajil.", "ngaliny kurrubijal yaluy nyajil | 1du.INCL.NOM morning.star here see.NPST", "r284_1du_incl_sky_celestial_here_see_kurrubijal", ["ngaliny", "kurrubijal", "yaluy", "nyajil"], EVIDENCE["kurrubijal"]),
    row(20, "You and I see the rainbow here.", "Ngaliny yiril yaluy nyajil.", "ngaliny yiril yaluy nyajil | 1du.INCL.NOM rainbow here see.NPST", "r284_1du_incl_sky_celestial_here_see_yiril", ["ngaliny", "yiril", "yaluy", "nyajil"], EVIDENCE["yiril"]),
    row(21, "You two see the lightning there.", "Yubal balbay yinyay nyajil.", "yubal balbay yinyay nyajil | 2du.NOM lightning there see.NPST", "r284_2du_sky_celestial_there_see_balbay", ["yubal", "balbay", "yinyay", "nyajil"], EVIDENCE["balbay"]),
    row(22, "You two see the shooting star there.", "Yubal binyu yinyay nyajil.", "yubal binyu yinyay nyajil | 2du.NOM shooting.star there see.NPST", "r284_2du_sky_celestial_there_see_binyu", ["yubal", "binyu", "yinyay", "nyajil"], EVIDENCE["binyu"]),
    row(23, "You two see the star there.", "Yubal dawar yinyay nyajil.", "yubal dawar yinyay nyajil | 2du.NOM star there see.NPST", "r284_2du_sky_celestial_there_see_dawar", ["yubal", "dawar", "yinyay", "nyajil"], EVIDENCE["dawar"]),
    row(24, "You two see the sky there.", "Yubal jiri yinyay nyajil.", "yubal jiri yinyay nyajil | 2du.NOM sky there see.NPST", "r284_2du_sky_celestial_there_see_jiri", ["yubal", "jiri", "yinyay", "nyajil"], EVIDENCE["jiri"]),
    row(25, "You two see the rain there.", "Yubal kaba yinyay nyajil.", "yubal kaba yinyay nyajil | 2du.NOM rain there see.NPST", "r284_2du_sky_celestial_there_see_kaba", ["yubal", "kaba", "yinyay", "nyajil"], EVIDENCE["kaba"]),
    row(26, "You two see the moon there.", "Yubal kija yinyay nyajil.", "yubal kija yinyay nyajil | 2du.NOM moon there see.NPST", "r284_2du_sky_celestial_there_see_kija", ["yubal", "kija", "yinyay", "nyajil"], EVIDENCE["kija"]),
    row(27, "You two see the sun there.", "Yubal wungar yinyay nyajil.", "yubal wungar yinyay nyajil | 2du.NOM sun there see.NPST", "r284_2du_sky_celestial_there_see_wungar", ["yubal", "wungar", "yinyay", "nyajil"], EVIDENCE["wungar"]),
    row(28, "You two see the mackerel sky there.", "Yubal kurrinkurrin yinyay nyajil.", "yubal kurrinkurrin yinyay nyajil | 2du.NOM mackerel.sky there see.NPST", "r284_2du_sky_celestial_there_see_kurrinkurrin", ["yubal", "kurrinkurrin", "yinyay", "nyajil"], EVIDENCE["kurrinkurrin"]),
    row(29, "You two see the morning star there.", "Yubal kurrubijal yinyay nyajil.", "yubal kurrubijal yinyay nyajil | 2du.NOM morning.star there see.NPST", "r284_2du_sky_celestial_there_see_kurrubijal", ["yubal", "kurrubijal", "yinyay", "nyajil"], EVIDENCE["kurrubijal"]),
    row(30, "You two see the rainbow there.", "Yubal yiril yinyay nyajil.", "yubal yiril yinyay nyajil | 2du.NOM rainbow there see.NPST", "r284_2du_sky_celestial_there_see_yiril", ["yubal", "yiril", "yinyay", "nyajil"], EVIDENCE["yiril"]),
    row(31, "You all see the lightning here.", "Yurra balbay yaluy nyajil.", "yurra balbay yaluy nyajil | 2pl.NOM lightning here see.NPST", "r284_2pl_sky_celestial_here_see_balbay", ["yurra", "balbay", "yaluy", "nyajil"], EVIDENCE["balbay"]),
    row(32, "You all see the shooting star here.", "Yurra binyu yaluy nyajil.", "yurra binyu yaluy nyajil | 2pl.NOM shooting.star here see.NPST", "r284_2pl_sky_celestial_here_see_binyu", ["yurra", "binyu", "yaluy", "nyajil"], EVIDENCE["binyu"]),
    row(33, "You all see the star here.", "Yurra dawar yaluy nyajil.", "yurra dawar yaluy nyajil | 2pl.NOM star here see.NPST", "r284_2pl_sky_celestial_here_see_dawar", ["yurra", "dawar", "yaluy", "nyajil"], EVIDENCE["dawar"]),
    row(34, "You all see the sky here.", "Yurra jiri yaluy nyajil.", "yurra jiri yaluy nyajil | 2pl.NOM sky here see.NPST", "r284_2pl_sky_celestial_here_see_jiri", ["yurra", "jiri", "yaluy", "nyajil"], EVIDENCE["jiri"]),
    row(35, "You all see the rain here.", "Yurra kaba yaluy nyajil.", "yurra kaba yaluy nyajil | 2pl.NOM rain here see.NPST", "r284_2pl_sky_celestial_here_see_kaba", ["yurra", "kaba", "yaluy", "nyajil"], EVIDENCE["kaba"]),
    row(36, "You all see the moon here.", "Yurra kija yaluy nyajil.", "yurra kija yaluy nyajil | 2pl.NOM moon here see.NPST", "r284_2pl_sky_celestial_here_see_kija", ["yurra", "kija", "yaluy", "nyajil"], EVIDENCE["kija"]),
    row(37, "You all see the sun here.", "Yurra wungar yaluy nyajil.", "yurra wungar yaluy nyajil | 2pl.NOM sun here see.NPST", "r284_2pl_sky_celestial_here_see_wungar", ["yurra", "wungar", "yaluy", "nyajil"], EVIDENCE["wungar"]),
    row(38, "You all see the mackerel sky here.", "Yurra kurrinkurrin yaluy nyajil.", "yurra kurrinkurrin yaluy nyajil | 2pl.NOM mackerel.sky here see.NPST", "r284_2pl_sky_celestial_here_see_kurrinkurrin", ["yurra", "kurrinkurrin", "yaluy", "nyajil"], EVIDENCE["kurrinkurrin"]),
    row(39, "You all see the morning star here.", "Yurra kurrubijal yaluy nyajil.", "yurra kurrubijal yaluy nyajil | 2pl.NOM morning.star here see.NPST", "r284_2pl_sky_celestial_here_see_kurrubijal", ["yurra", "kurrubijal", "yaluy", "nyajil"], EVIDENCE["kurrubijal"]),
    row(40, "You all see the rainbow here.", "Yurra yiril yaluy nyajil.", "yurra yiril yaluy nyajil | 2pl.NOM rainbow here see.NPST", "r284_2pl_sky_celestial_here_see_yiril", ["yurra", "yiril", "yaluy", "nyajil"], EVIDENCE["yiril"]),
    row(41, "They see the lightning there.", "Jana balbay yinyay nyajil.", "jana balbay yinyay nyajil | 3pl.NOM lightning there see.NPST", "r284_3pl_sky_celestial_there_see_balbay", ["jana", "balbay", "yinyay", "nyajil"], EVIDENCE["balbay"]),
    row(42, "They see the shooting star there.", "Jana binyu yinyay nyajil.", "jana binyu yinyay nyajil | 3pl.NOM shooting.star there see.NPST", "r284_3pl_sky_celestial_there_see_binyu", ["jana", "binyu", "yinyay", "nyajil"], EVIDENCE["binyu"]),
    row(43, "They see the star there.", "Jana dawar yinyay nyajil.", "jana dawar yinyay nyajil | 3pl.NOM star there see.NPST", "r284_3pl_sky_celestial_there_see_dawar", ["jana", "dawar", "yinyay", "nyajil"], EVIDENCE["dawar"]),
    row(44, "They see the sky there.", "Jana jiri yinyay nyajil.", "jana jiri yinyay nyajil | 3pl.NOM sky there see.NPST", "r284_3pl_sky_celestial_there_see_jiri", ["jana", "jiri", "yinyay", "nyajil"], EVIDENCE["jiri"]),
    row(45, "They see the rain there.", "Jana kaba yinyay nyajil.", "jana kaba yinyay nyajil | 3pl.NOM rain there see.NPST", "r284_3pl_sky_celestial_there_see_kaba", ["jana", "kaba", "yinyay", "nyajil"], EVIDENCE["kaba"]),
    row(46, "They see the moon there.", "Jana kija yinyay nyajil.", "jana kija yinyay nyajil | 3pl.NOM moon there see.NPST", "r284_3pl_sky_celestial_there_see_kija", ["jana", "kija", "yinyay", "nyajil"], EVIDENCE["kija"]),
    row(47, "They see the sun there.", "Jana wungar yinyay nyajil.", "jana wungar yinyay nyajil | 3pl.NOM sun there see.NPST", "r284_3pl_sky_celestial_there_see_wungar", ["jana", "wungar", "yinyay", "nyajil"], EVIDENCE["wungar"]),
    row(48, "They see the mackerel sky there.", "Jana kurrinkurrin yinyay nyajil.", "jana kurrinkurrin yinyay nyajil | 3pl.NOM mackerel.sky there see.NPST", "r284_3pl_sky_celestial_there_see_kurrinkurrin", ["jana", "kurrinkurrin", "yinyay", "nyajil"], EVIDENCE["kurrinkurrin"]),
    row(49, "They see the morning star there.", "Jana kurrubijal yinyay nyajil.", "jana kurrubijal yinyay nyajil | 3pl.NOM morning.star there see.NPST", "r284_3pl_sky_celestial_there_see_kurrubijal", ["jana", "kurrubijal", "yinyay", "nyajil"], EVIDENCE["kurrubijal"]),
    row(50, "They see the rainbow there.", "Jana yiril yinyay nyajil.", "jana yiril yinyay nyajil | 3pl.NOM rainbow there see.NPST", "r284_3pl_sky_celestial_there_see_yiril", ["jana", "yiril", "yinyay", "nyajil"], EVIDENCE["yiril"]),
]

EXPECTED_BANDS = [
    ("ngali", "yinyay"),
    ("ngaliny", "yaluy"),
    ("yubal", "yinyay"),
    ("yurra", "yaluy"),
    ("jana", "yinyay"),
]


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}")
        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 len([w for w in ("yaluy", "yinyay") if w in words]) != 1:
            issues.append(f"{seq}: demonstrative problem {words}")
        expected_pronoun, expected_demo = EXPECTED_BANDS[(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] not in TARGET_HEADS:
            issues.append(f"{seq}: word 2 is not a target {words[1]}")
        if words[3] != "nyajil":
            issues.append(f"{seq}: word 4 is not nyajil {words[3]}")
        if not frame.startswith("r284_"):
            issues.append(f"{seq}: frame not r284 {frame}")
    return issues


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 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", "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 = (
        "VISIBLE SKY/CELESTIAL NON-SINGULAR NONPAST PRONOUN PERCEPTION SWEEP AFTER RULE 283 "
        "(Rule 284). 50 under-review rows over balbay lightning, binyu shooting star, dawar star, jiri sky, "
        "kaba rain, kija moon, wungar sun, kurrinkurrin mackerel sky, kurrubijal morning star, and yiril rainbow "
        "with bare nominative ngali, ngaliny, yubal, yurra, and jana. Ngurrban was rejected after exact duplicate "
        "pressure; wungar fills the final sky/celestial slot. Only bare visual nonpast reference/perception rows are "
        "opened; moon month/place/story, lightning-strike, death-spirit/death-omen, heaven/sky-mob/fine-day "
        "compounds, rain events, sun-time/hot-season compounds, rainbow story/snake/water-hole extensions, target "
        "case, pronoun case, demonstrative case, compounds, productive reduplication, 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 284 under review", "operator-guide-2026-07-09", 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 dictionary source lines for final visible sky/celestial targets, including kija as visible moon and wungar as the ngurrban replacement, and Patz non-singular pronoun, demonstrative, and nyaji-l nonpast support before authoring.", 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 a visible sky/celestial non-singular nonpast pronoun perception sweep after Rule 283. Initial ngurrban candidate was rejected after Batch 195 duplicate pressure; sourced wungar sun fills the final slot.", 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="Initial target set with ngurrban found duplicate Jana ngurrban yinyay nyajil. from Batch 195; final 50 Rule 284 surfaces with wungar and kija 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 rows, one target each, bare non-singular nominative pronouns, bare yaluy/yinyay, final nyajil, no loans, no denied Kuku forms, no ngurrban/place-story/death-omen/strike/weather-event/time-compound drift.", command="python3 -m py_compile batch_scripts/bank_326.py && python3 -c \"import sys; sys.path.insert(0,'batch_scripts'); import bank_326; print(bank_326.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_326.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main", detail=f"Banked 50 Rule 284 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_326.py", output_excerpt=f"banked batch-326: 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-326: 50 rows under_review")
    return 0


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