#!/usr/bin/env python3
"""Bank batch-358: Rule 316 low-coverage bird 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-358"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-358-low-coverage-bird-nonsingular-nonpast-perception-after-rule315-process.md"

TARGET_EVIDENCE = {
    "dabway": "Dictionary yaml lines 4465-4483 give dabway as noun 'black bird' / 'black messenger bird', with source prose identifying it as a totem of dabu and walarr moieties. Rule 316 selects visible dabway-bird reference only and leaves colour, messenger behavior, totem, moiety, warning, omen, and event rows closed.",
    "kalmnbagarr": "Dictionary yaml lines 12800-12808 give kalmnbagarr as noun 'black diver bird'. Rule 316 selects visible kalmnbagarr diver-bird reference only and leaves colour, diving behavior, water habitat, and event rows closed.",
    "kurkunbay": "Dictionary yaml lines 16134-16143 give kurkunbay as noun 'butcherbird' / 'stockwhip bird'. Rule 316 selects visible kurkunbay butcherbird reference only and leaves stockwhip-call, sound, behavior, hunting, omen, and event rows closed.",
    "kurrburrubun": "Dictionary yaml lines 16345-16363 give kurrburrubun as noun 'magpie'. Rule 316 selects visible kurrburrubun-magpie reference only and leaves call, song, feeding, behavior, and event rows closed.",
    "kurrujuwa": "Dictionary yaml lines 16594-16613 give kurrujuwa as noun 'sentry bird', with source prose about warning of crocodiles along river banks and totem status for dabu and walarr. Rule 316 selects visible kurrujuwa-bird reference only and leaves warning, crocodile, river-bank, danger, totem, moiety, behavior, and event rows closed.",
    "mirrki": "Dictionary yaml lines 19792-19801 give mirrki as noun 'kidney bird'. Rule 316 selects visible mirrki kidney-bird reference only and leaves anatomy, kidney association, call, behavior, and event rows closed.",
    "mirrku": "Dictionary yaml lines 19802-19813 give mirrku as noun 'kidney bird', identified in source prose as a dabu-moiety totem. Rule 316 selects visible mirrku kidney-bird reference only and leaves anatomy, totem, moiety, call, behavior, and event rows closed.",
    "mulumu": "Dictionary yaml lines 20512-20524 give mulumu as noun 'dove' and a secondary sense 'wood used in a sacred corroboree'. Rule 316 selects visible mulumu-dove reference only and leaves wood, sacred, ceremony/corroboree, material, use, and event rows closed.",
    "munungkul": "Dictionary yaml lines 20827-20835 give munungkul as noun 'ground pigeon'. Rule 316 selects visible ground-pigeon reference only and does not inherit feeding, leaves, shade, tree, ground-habitat, or behavior propositions from its single earlier corpus use.",
    "ngarkay": "Dictionary yaml lines 22729-22748 give ngarkay as noun 'waterhen' / 'water hen'. Rule 316 selects visible waterhen reference only and does not inherit grass, swamp-edge, walking, mud, hunting, prey, habitat, or behavior propositions from its single earlier corpus use.",
}

SUPPORT_EVIDENCE = (
    "Living grammar pronoun table lines 2577-2582 sources bare nominatives ngali, ngaliny, yubal, yurra, and ngana; "
    "lines 2674-2684 support dual/plural person-number and inclusive/exclusive values. Demonstrative lines 2834-2847 "
    "source Yalanji yaluy 'here' and yinyay 'there'. Lines 3043-3049 give nyaji-l as nonpast 'see', lines 3149-3151 "
    "define nonpast present/future function, and lines 4256-4265 license nominative pronoun A with bare absolutive O "
    "for sensory perception. Dictionary lines 24282-24296 independently attest running-form nyajil as a general "
    "l-conjugation perception verb including visual 'see'. Rule 316 uses only bare forms and the visual sense."
)

TARGET_ORDER = ["dabway", "kalmnbagarr", "kurkunbay", "kurrburrubun", "kurrujuwa", "mirrki", "mirrku", "mulumu", "munungkul", "ngarkay"]
TARGET_LABELS = {
    "dabway": "dabway bird",
    "kalmnbagarr": "kalmnbagarr diver bird",
    "kurkunbay": "kurkunbay butcherbird",
    "kurrburrubun": "kurrburrubun magpie",
    "kurrujuwa": "kurrujuwa sentry bird",
    "mirrki": "mirrki kidney bird",
    "mirrku": "mirrku kidney bird",
    "mulumu": "mulumu dove",
    "munungkul": "munungkul ground pigeon",
    "ngarkay": "ngarkay waterhen",
}
FRAME_SPECS = [
    ("ngali", "yaluy", "We two, not you, see", "here"),
    ("ngaliny", "yinyay", "You and I see", "there"),
    ("yubal", "yaluy", "You two see", "here"),
    ("yurra", "yinyay", "You all see", "there"),
    ("ngana", "yaluy", "We see", "here"),
]

DENY_KUKU = {
    "ngayu", "yundu", "nyulu", "yulu", "bula", "jana", "nganjin", "iana",
    "ngalingan", "ngalinyan", "yubalan", "ngalininy", "ngalinyiny", "yubaliny",
    "ngalinka", "ngalinyanka", "yubalanka", "ngalinda", "ngalinyanda", "yubalanda",
    "ngalindamuny", "ngalinyandamuny", "yubalandamuny", "ngalinji", "ngalinyanji", "yubalanji",
    "ngalinga", "ngalinyanga", "yubalanga", "yurrangan", "yurraniny", "yurranka", "yurranda",
    "yurrandamuny", "yurranji", "yurranga", "nganangan", "ngananiny", "ngananka", "ngananda",
    "nganandamuny", "ngananji", "ngananga",
    "bidubidu", "binjurrbinjurr", "dibirrdibirr", "jukujuku", "muya", "kumurbina", "burrkul", "bulbul",
    "miyilabu", "ngalkarran", "wada", "wangku", "yinkunji", "yurrunji", "jajikal", "jalnji", "jinjay", "kurubarr",
    "yalungku", "yaluyngku", "yinyangka", "yinyayngka", "yalamuny", "yinyamuny",
    "nyajin", "nyajiny", "nyaji-ny", "nyaji-nka", "nyaji-l-nyaji", "milka", "baykal", "jalngkay",
}
DENY_ENGLISH = (
    "black", "messenger", "totem", "dabu", "walarr", "moiety", "stockwhip", "call", "song", "sing",
    "warning", "warn", "crocodile", "river", "bank", "danger", "omen", "anatomy", "wood",
    "sacred", "corroboree", "ceremony", "material", "use", "used", "feeding", "feed", "leaves", "shade",
    "tree", "ground-habitat", "habitat", "grass", "swamp", "edge", "walking", "walk", "mud", "hunt",
    "hunting", "prey", "behavior", "event", "water",
)


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]
    return (seq, english, kuku, analysis, frame, 3, json.dumps(words, ensure_ascii=False), json.dumps([], ensure_ascii=False), f"{TARGET_EVIDENCE[target]} {SUPPORT_EVIDENCE}", "0.86")


ROWS = [
    row(1, "We two, not you, see the dabway bird here.", "Ngali dabway yaluy nyajil.", "ngali dabway yaluy nyajil | 1du.excl.NOM dabway.bird here see.NPST", "r316_1du_excl_here_low_bird_see_dabway", ["ngali", "dabway", "yaluy", "nyajil"]),
    row(2, "We two, not you, see the kalmnbagarr diver bird here.", "Ngali kalmnbagarr yaluy nyajil.", "ngali kalmnbagarr yaluy nyajil | 1du.excl.NOM kalmnbagarr.diver.bird here see.NPST", "r316_1du_excl_here_low_bird_see_kalmnbagarr", ["ngali", "kalmnbagarr", "yaluy", "nyajil"]),
    row(3, "We two, not you, see the kurkunbay butcherbird here.", "Ngali kurkunbay yaluy nyajil.", "ngali kurkunbay yaluy nyajil | 1du.excl.NOM kurkunbay.butcherbird here see.NPST", "r316_1du_excl_here_low_bird_see_kurkunbay", ["ngali", "kurkunbay", "yaluy", "nyajil"]),
    row(4, "We two, not you, see the kurrburrubun magpie here.", "Ngali kurrburrubun yaluy nyajil.", "ngali kurrburrubun yaluy nyajil | 1du.excl.NOM kurrburrubun.magpie here see.NPST", "r316_1du_excl_here_low_bird_see_kurrburrubun", ["ngali", "kurrburrubun", "yaluy", "nyajil"]),
    row(5, "We two, not you, see the kurrujuwa sentry bird here.", "Ngali kurrujuwa yaluy nyajil.", "ngali kurrujuwa yaluy nyajil | 1du.excl.NOM kurrujuwa.sentry.bird here see.NPST", "r316_1du_excl_here_low_bird_see_kurrujuwa", ["ngali", "kurrujuwa", "yaluy", "nyajil"]),
    row(6, "We two, not you, see the mirrki kidney bird here.", "Ngali mirrki yaluy nyajil.", "ngali mirrki yaluy nyajil | 1du.excl.NOM mirrki.kidney.bird here see.NPST", "r316_1du_excl_here_low_bird_see_mirrki", ["ngali", "mirrki", "yaluy", "nyajil"]),
    row(7, "We two, not you, see the mirrku kidney bird here.", "Ngali mirrku yaluy nyajil.", "ngali mirrku yaluy nyajil | 1du.excl.NOM mirrku.kidney.bird here see.NPST", "r316_1du_excl_here_low_bird_see_mirrku", ["ngali", "mirrku", "yaluy", "nyajil"]),
    row(8, "We two, not you, see the mulumu dove here.", "Ngali mulumu yaluy nyajil.", "ngali mulumu yaluy nyajil | 1du.excl.NOM mulumu.dove here see.NPST", "r316_1du_excl_here_low_bird_see_mulumu", ["ngali", "mulumu", "yaluy", "nyajil"]),
    row(9, "We two, not you, see the munungkul ground pigeon here.", "Ngali munungkul yaluy nyajil.", "ngali munungkul yaluy nyajil | 1du.excl.NOM munungkul.ground.pigeon here see.NPST", "r316_1du_excl_here_low_bird_see_munungkul", ["ngali", "munungkul", "yaluy", "nyajil"]),
    row(10, "We two, not you, see the ngarkay waterhen here.", "Ngali ngarkay yaluy nyajil.", "ngali ngarkay yaluy nyajil | 1du.excl.NOM ngarkay.waterhen here see.NPST", "r316_1du_excl_here_low_bird_see_ngarkay", ["ngali", "ngarkay", "yaluy", "nyajil"]),
    row(11, "You and I see the dabway bird there.", "Ngaliny dabway yinyay nyajil.", "ngaliny dabway yinyay nyajil | 1du.incl.NOM dabway.bird there see.NPST", "r316_1du_incl_there_low_bird_see_dabway", ["ngaliny", "dabway", "yinyay", "nyajil"]),
    row(12, "You and I see the kalmnbagarr diver bird there.", "Ngaliny kalmnbagarr yinyay nyajil.", "ngaliny kalmnbagarr yinyay nyajil | 1du.incl.NOM kalmnbagarr.diver.bird there see.NPST", "r316_1du_incl_there_low_bird_see_kalmnbagarr", ["ngaliny", "kalmnbagarr", "yinyay", "nyajil"]),
    row(13, "You and I see the kurkunbay butcherbird there.", "Ngaliny kurkunbay yinyay nyajil.", "ngaliny kurkunbay yinyay nyajil | 1du.incl.NOM kurkunbay.butcherbird there see.NPST", "r316_1du_incl_there_low_bird_see_kurkunbay", ["ngaliny", "kurkunbay", "yinyay", "nyajil"]),
    row(14, "You and I see the kurrburrubun magpie there.", "Ngaliny kurrburrubun yinyay nyajil.", "ngaliny kurrburrubun yinyay nyajil | 1du.incl.NOM kurrburrubun.magpie there see.NPST", "r316_1du_incl_there_low_bird_see_kurrburrubun", ["ngaliny", "kurrburrubun", "yinyay", "nyajil"]),
    row(15, "You and I see the kurrujuwa sentry bird there.", "Ngaliny kurrujuwa yinyay nyajil.", "ngaliny kurrujuwa yinyay nyajil | 1du.incl.NOM kurrujuwa.sentry.bird there see.NPST", "r316_1du_incl_there_low_bird_see_kurrujuwa", ["ngaliny", "kurrujuwa", "yinyay", "nyajil"]),
    row(16, "You and I see the mirrki kidney bird there.", "Ngaliny mirrki yinyay nyajil.", "ngaliny mirrki yinyay nyajil | 1du.incl.NOM mirrki.kidney.bird there see.NPST", "r316_1du_incl_there_low_bird_see_mirrki", ["ngaliny", "mirrki", "yinyay", "nyajil"]),
    row(17, "You and I see the mirrku kidney bird there.", "Ngaliny mirrku yinyay nyajil.", "ngaliny mirrku yinyay nyajil | 1du.incl.NOM mirrku.kidney.bird there see.NPST", "r316_1du_incl_there_low_bird_see_mirrku", ["ngaliny", "mirrku", "yinyay", "nyajil"]),
    row(18, "You and I see the mulumu dove there.", "Ngaliny mulumu yinyay nyajil.", "ngaliny mulumu yinyay nyajil | 1du.incl.NOM mulumu.dove there see.NPST", "r316_1du_incl_there_low_bird_see_mulumu", ["ngaliny", "mulumu", "yinyay", "nyajil"]),
    row(19, "You and I see the munungkul ground pigeon there.", "Ngaliny munungkul yinyay nyajil.", "ngaliny munungkul yinyay nyajil | 1du.incl.NOM munungkul.ground.pigeon there see.NPST", "r316_1du_incl_there_low_bird_see_munungkul", ["ngaliny", "munungkul", "yinyay", "nyajil"]),
    row(20, "You and I see the ngarkay waterhen there.", "Ngaliny ngarkay yinyay nyajil.", "ngaliny ngarkay yinyay nyajil | 1du.incl.NOM ngarkay.waterhen there see.NPST", "r316_1du_incl_there_low_bird_see_ngarkay", ["ngaliny", "ngarkay", "yinyay", "nyajil"]),
    row(21, "You two see the dabway bird here.", "Yubal dabway yaluy nyajil.", "yubal dabway yaluy nyajil | 2du.NOM dabway.bird here see.NPST", "r316_2du_here_low_bird_see_dabway", ["yubal", "dabway", "yaluy", "nyajil"]),
    row(22, "You two see the kalmnbagarr diver bird here.", "Yubal kalmnbagarr yaluy nyajil.", "yubal kalmnbagarr yaluy nyajil | 2du.NOM kalmnbagarr.diver.bird here see.NPST", "r316_2du_here_low_bird_see_kalmnbagarr", ["yubal", "kalmnbagarr", "yaluy", "nyajil"]),
    row(23, "You two see the kurkunbay butcherbird here.", "Yubal kurkunbay yaluy nyajil.", "yubal kurkunbay yaluy nyajil | 2du.NOM kurkunbay.butcherbird here see.NPST", "r316_2du_here_low_bird_see_kurkunbay", ["yubal", "kurkunbay", "yaluy", "nyajil"]),
    row(24, "You two see the kurrburrubun magpie here.", "Yubal kurrburrubun yaluy nyajil.", "yubal kurrburrubun yaluy nyajil | 2du.NOM kurrburrubun.magpie here see.NPST", "r316_2du_here_low_bird_see_kurrburrubun", ["yubal", "kurrburrubun", "yaluy", "nyajil"]),
    row(25, "You two see the kurrujuwa sentry bird here.", "Yubal kurrujuwa yaluy nyajil.", "yubal kurrujuwa yaluy nyajil | 2du.NOM kurrujuwa.sentry.bird here see.NPST", "r316_2du_here_low_bird_see_kurrujuwa", ["yubal", "kurrujuwa", "yaluy", "nyajil"]),
    row(26, "You two see the mirrki kidney bird here.", "Yubal mirrki yaluy nyajil.", "yubal mirrki yaluy nyajil | 2du.NOM mirrki.kidney.bird here see.NPST", "r316_2du_here_low_bird_see_mirrki", ["yubal", "mirrki", "yaluy", "nyajil"]),
    row(27, "You two see the mirrku kidney bird here.", "Yubal mirrku yaluy nyajil.", "yubal mirrku yaluy nyajil | 2du.NOM mirrku.kidney.bird here see.NPST", "r316_2du_here_low_bird_see_mirrku", ["yubal", "mirrku", "yaluy", "nyajil"]),
    row(28, "You two see the mulumu dove here.", "Yubal mulumu yaluy nyajil.", "yubal mulumu yaluy nyajil | 2du.NOM mulumu.dove here see.NPST", "r316_2du_here_low_bird_see_mulumu", ["yubal", "mulumu", "yaluy", "nyajil"]),
    row(29, "You two see the munungkul ground pigeon here.", "Yubal munungkul yaluy nyajil.", "yubal munungkul yaluy nyajil | 2du.NOM munungkul.ground.pigeon here see.NPST", "r316_2du_here_low_bird_see_munungkul", ["yubal", "munungkul", "yaluy", "nyajil"]),
    row(30, "You two see the ngarkay waterhen here.", "Yubal ngarkay yaluy nyajil.", "yubal ngarkay yaluy nyajil | 2du.NOM ngarkay.waterhen here see.NPST", "r316_2du_here_low_bird_see_ngarkay", ["yubal", "ngarkay", "yaluy", "nyajil"]),
    row(31, "You all see the dabway bird there.", "Yurra dabway yinyay nyajil.", "yurra dabway yinyay nyajil | 2pl.NOM dabway.bird there see.NPST", "r316_2pl_there_low_bird_see_dabway", ["yurra", "dabway", "yinyay", "nyajil"]),
    row(32, "You all see the kalmnbagarr diver bird there.", "Yurra kalmnbagarr yinyay nyajil.", "yurra kalmnbagarr yinyay nyajil | 2pl.NOM kalmnbagarr.diver.bird there see.NPST", "r316_2pl_there_low_bird_see_kalmnbagarr", ["yurra", "kalmnbagarr", "yinyay", "nyajil"]),
    row(33, "You all see the kurkunbay butcherbird there.", "Yurra kurkunbay yinyay nyajil.", "yurra kurkunbay yinyay nyajil | 2pl.NOM kurkunbay.butcherbird there see.NPST", "r316_2pl_there_low_bird_see_kurkunbay", ["yurra", "kurkunbay", "yinyay", "nyajil"]),
    row(34, "You all see the kurrburrubun magpie there.", "Yurra kurrburrubun yinyay nyajil.", "yurra kurrburrubun yinyay nyajil | 2pl.NOM kurrburrubun.magpie there see.NPST", "r316_2pl_there_low_bird_see_kurrburrubun", ["yurra", "kurrburrubun", "yinyay", "nyajil"]),
    row(35, "You all see the kurrujuwa sentry bird there.", "Yurra kurrujuwa yinyay nyajil.", "yurra kurrujuwa yinyay nyajil | 2pl.NOM kurrujuwa.sentry.bird there see.NPST", "r316_2pl_there_low_bird_see_kurrujuwa", ["yurra", "kurrujuwa", "yinyay", "nyajil"]),
    row(36, "You all see the mirrki kidney bird there.", "Yurra mirrki yinyay nyajil.", "yurra mirrki yinyay nyajil | 2pl.NOM mirrki.kidney.bird there see.NPST", "r316_2pl_there_low_bird_see_mirrki", ["yurra", "mirrki", "yinyay", "nyajil"]),
    row(37, "You all see the mirrku kidney bird there.", "Yurra mirrku yinyay nyajil.", "yurra mirrku yinyay nyajil | 2pl.NOM mirrku.kidney.bird there see.NPST", "r316_2pl_there_low_bird_see_mirrku", ["yurra", "mirrku", "yinyay", "nyajil"]),
    row(38, "You all see the mulumu dove there.", "Yurra mulumu yinyay nyajil.", "yurra mulumu yinyay nyajil | 2pl.NOM mulumu.dove there see.NPST", "r316_2pl_there_low_bird_see_mulumu", ["yurra", "mulumu", "yinyay", "nyajil"]),
    row(39, "You all see the munungkul ground pigeon there.", "Yurra munungkul yinyay nyajil.", "yurra munungkul yinyay nyajil | 2pl.NOM munungkul.ground.pigeon there see.NPST", "r316_2pl_there_low_bird_see_munungkul", ["yurra", "munungkul", "yinyay", "nyajil"]),
    row(40, "You all see the ngarkay waterhen there.", "Yurra ngarkay yinyay nyajil.", "yurra ngarkay yinyay nyajil | 2pl.NOM ngarkay.waterhen there see.NPST", "r316_2pl_there_low_bird_see_ngarkay", ["yurra", "ngarkay", "yinyay", "nyajil"]),
    row(41, "We see the dabway bird here.", "Ngana dabway yaluy nyajil.", "ngana dabway yaluy nyajil | 1pl.incl.NOM dabway.bird here see.NPST", "r316_1pl_incl_here_low_bird_see_dabway", ["ngana", "dabway", "yaluy", "nyajil"]),
    row(42, "We see the kalmnbagarr diver bird here.", "Ngana kalmnbagarr yaluy nyajil.", "ngana kalmnbagarr yaluy nyajil | 1pl.incl.NOM kalmnbagarr.diver.bird here see.NPST", "r316_1pl_incl_here_low_bird_see_kalmnbagarr", ["ngana", "kalmnbagarr", "yaluy", "nyajil"]),
    row(43, "We see the kurkunbay butcherbird here.", "Ngana kurkunbay yaluy nyajil.", "ngana kurkunbay yaluy nyajil | 1pl.incl.NOM kurkunbay.butcherbird here see.NPST", "r316_1pl_incl_here_low_bird_see_kurkunbay", ["ngana", "kurkunbay", "yaluy", "nyajil"]),
    row(44, "We see the kurrburrubun magpie here.", "Ngana kurrburrubun yaluy nyajil.", "ngana kurrburrubun yaluy nyajil | 1pl.incl.NOM kurrburrubun.magpie here see.NPST", "r316_1pl_incl_here_low_bird_see_kurrburrubun", ["ngana", "kurrburrubun", "yaluy", "nyajil"]),
    row(45, "We see the kurrujuwa sentry bird here.", "Ngana kurrujuwa yaluy nyajil.", "ngana kurrujuwa yaluy nyajil | 1pl.incl.NOM kurrujuwa.sentry.bird here see.NPST", "r316_1pl_incl_here_low_bird_see_kurrujuwa", ["ngana", "kurrujuwa", "yaluy", "nyajil"]),
    row(46, "We see the mirrki kidney bird here.", "Ngana mirrki yaluy nyajil.", "ngana mirrki yaluy nyajil | 1pl.incl.NOM mirrki.kidney.bird here see.NPST", "r316_1pl_incl_here_low_bird_see_mirrki", ["ngana", "mirrki", "yaluy", "nyajil"]),
    row(47, "We see the mirrku kidney bird here.", "Ngana mirrku yaluy nyajil.", "ngana mirrku yaluy nyajil | 1pl.incl.NOM mirrku.kidney.bird here see.NPST", "r316_1pl_incl_here_low_bird_see_mirrku", ["ngana", "mirrku", "yaluy", "nyajil"]),
    row(48, "We see the mulumu dove here.", "Ngana mulumu yaluy nyajil.", "ngana mulumu yaluy nyajil | 1pl.incl.NOM mulumu.dove here see.NPST", "r316_1pl_incl_here_low_bird_see_mulumu", ["ngana", "mulumu", "yaluy", "nyajil"]),
    row(49, "We see the munungkul ground pigeon here.", "Ngana munungkul yaluy nyajil.", "ngana munungkul yaluy nyajil | 1pl.incl.NOM munungkul.ground.pigeon here see.NPST", "r316_1pl_incl_here_low_bird_see_munungkul", ["ngana", "munungkul", "yaluy", "nyajil"]),
    row(50, "We see the ngarkay waterhen here.", "Ngana ngarkay yaluy nyajil.", "ngana ngarkay yaluy nyajil | 1pl.incl.NOM ngarkay.waterhen here see.NPST", "r316_1pl_incl_here_low_bird_see_ngarkay", ["ngana", "ngarkay", "yaluy", "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")
    if len({r[2] for r in ROWS}) != 50:
        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)
        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}."
        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)}\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("r316_"):
            issues.append(f"{seq}: frame not r316 {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 = (
        "LOW-COVERAGE BIRD NON-SINGULAR NONPAST PERCEPTION SWEEP AFTER RULE 315 (Rule 316). 50 under-review rows "
        "over eight zero-use and two one-use direct-dictionary bird heads: dabway, kalmnbagarr, kurkunbay, "
        "kurrburrubun, kurrujuwa, mirrki, mirrku, mulumu, munungkul, and ngarkay. SUPPORT: bare nominative ngali, "
        "ngaliny, yubal, yurra, and ngana, Yalanji yaluy/yinyay, and dictionary-attested nonpast nyajil. Only bare "
        "visible bird perception/reference is opened; colour, messenger/totem/moiety, calls, warning/crocodile/danger, "
        "ceremonial wood, feeding, habitat, hunting, 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 316 under review", "operator-guide-2026-07-10", notes, NOW))
    batch_id = cur.lastrowid
    db.executemany(
        """INSERT INTO sentences(batch_id,seq,english,kuku,analysis,frame,tier,words_used,loans_used,evidence,status,confidence,rights_status,author,created_at,updated_at)
           VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
        [(batch_id,seq,english,kuku,analysis,frame,tier,words_used,loans_used,evidence,"under_review",confidence,"project_approved_synthetic_pending_elder_verification","codex-main",NOW,NOW)
         for seq,english,kuku,analysis,frame,tier,words_used,loans_used,evidence,confidence in ROWS],
    )
    record_event(db, batch_label=LABEL, phase="source", event_type="source-readback", actor="codex", detail="Reread direct dictionary yaml entries for ten Rule 316 low-coverage bird targets, dictionary nyajil, and Patz non-singular pronoun, demonstrative, nonpast, and sensory-perception A/O evidence before authoring.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="planning", event_type="low-coverage-bird-nonsingular-nonpast-scope", actor="codex", detail="Selected eight zero-use and two one-use lint-safe direct-dictionary bird heads for bare non-singular nonpast visual perception. Excluded unsupported solid reduplications and closed colour, messenger/totem/moiety, call, warning/crocodile, danger, ceremonial wood, feeding, habitat, hunting, case, compound, tense, 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: 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 316 bird 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="codex", detail="Static guard passed: 50 explicit hand-authored rows, exact per-sequence Kuku and English contracts, one selected bird each, bare non-singular nominative pronoun bands, bare yaluy/yinyay, final nyajil, no loans, no denied Kuku forms, and no commentary/behavior drift.", command="python3 -m py_compile batch_scripts/bank_358.py && python3 -c \"import sys;sys.path.insert(0,'batch_scripts');import bank_358;print(bank_358.scan_static())\"", output_excerpt="issues 0", artifact_path="batch_scripts/bank_358.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="codex", detail=f"Banked 50 Rule 316 rows as under_review. Verified total remains {verified_before}; Kuku word count remains {words_before}.", command="python3 batch_scripts/bank_358.py", output_excerpt=f"banked batch-358: 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-358: 50 rows under_review")
    return 0


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