#!/usr/bin/env python3
"""Bank batch-384: Rule 342 sense-qualified reptile lexeme-set-C singular/third past 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-384"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-384-sense-qualified-reptile-set-c-singular-third-past-perception-after-rule341-process.md"

TARGET_EVIDENCE = {
    "kalkamuku": "Dictionary yaml lines 12625-12645 contain two exact fauna-reptile kalkamuku green-tree-snake records. Rule 342 uses generic kalkamuku snake reference without record collapse, colour/tree habitat, movement, diet, danger, source, possession, or events.",
    "karrkurr": "Dictionary yaml lines 13659-13670 give karrkurr as a green-frog noun. Prior corpus rows contain rain, calling, swamp, feeding, song, swimming, touch, and water-sign narratives. Rule 342 uses generic karrkurr frog only; colour, habitat, season/weather, sound, food, body/touch, cultural knowledge, source, possession, and events remain closed.",
    "jinkalmu": "Dictionary yaml lines 9600-9625 contain two exact brown-snake/taipan records, explicitly not distinguishing those taxa; one carries boys-eating-eyes/fierce-fighter prose. Patz 3932 and 5708 contain biting/killing contexts. Rule 342 uses generic jinkalmu snake only; species resolution, eyes/body, boys/eating, fierceness/fighting, biting/killing, source, possession, and events remain closed.",
    "barka": "Dictionary yaml lines 1745-1777 contain two snake records and a Queensland-nut flora record; the first record itself mixes nut and yellow-water-snake definitions. Rule 342 selects generic barka snake only; nut/tree/fruit/season, record alignment, colour/water habitat, food, source, possession, and events remain closed.",
    "yalnga": "Dictionary yaml lines 29117-29129 give yalnga as sea turtle with food-safety prose about poisonous sacs. Rule 342 uses generic yalnga turtle reference only; sea habitat, poison/danger, sacs/body, removal/butchery, food, source, possession, and events remain closed.",
    "biwul": "Dictionary yaml lines 3300-3325 distinguish biwul mother-in-law/avoidance-language and black-snake records; Patz 2261-2289 attests the kinship sense. Rule 342 selects generic biwul snake only; kinship/in-law, avoidance language, colour/size comparison, source, possession, case, social events, and danger remain closed.",
    "yirku-yirku": "Dictionary yaml lines 30457-30470 give exact fully reduplicated/onomatopoeic yirku-yirku as frog. Rule 342 uses the whole frog head only; free base, productive reduplication, sound imitation, habitat, source, possession, and events remain closed.",
    "jadi": "Dictionary yaml lines 7015-7026 give jadi as sand goanna with a food taboo restricting eating to old people. Rule 342 uses generic jadi goanna only; sand habitat, age/social permission, taboo, eating/food, hunting, source, possession, and events remain closed.",
    "walkarr": "Dictionary yaml lines 25492-25503 give walkarr as black scrub goanna; Patz 1616 attests walkarr-angka. Rule 342 uses generic bare walkarr goanna only; colour/scrub habitat, ergative case, size, hunting/food, source, possession, and events remain closed.",
    "bajabaja": "Dictionary yaml lines 293-307 give exact fully reduplicated bajabaja as blue-tongue lizard and a spring/place/story-site sense. Patz 719 and 3932 add creation-myth and biting/fighting contexts. Rule 342 uses the whole generic lizard head only; free base, place/story, colour/body, eggs/hatching/river/rocks, biting/fighting/killing, source, possession, and events remain closed.",
}

SUPPORT_EVIDENCE = (
    "Patz lines 2577-2584 source bare nominative ngayu, yundu, nyulu, bula, and running examples establish jana; "
    "2834-2847 source Yalanji yaluy/yinyay; 2021-2024 and 2568-2571 attest nyaji-ny; 3160-3162 define past -ny; "
    "4256-4265 license nominative pronoun A with bare absolutive O in perception; dictionary 23876-23883 and "
    "23968-23976 contain running nyajin. Patz target hits for walkarr, biwul, bajabaja, and jinkalmu attest forms "
    "or delimit non-selected kinship, myth, bite, kill, case, and event contexts; none is copied as a Rule 342 event."
)

TARGET_ORDER = ["kalkamuku", "karrkurr", "jinkalmu", "barka", "yalnga", "biwul", "yirku-yirku", "jadi", "walkarr", "bajabaja"]
TARGET_LABELS = {"kalkamuku": "kalkamuku snake", "karrkurr": "karrkurr frog", "jinkalmu": "jinkalmu snake", "barka": "barka snake", "yalnga": "yalnga turtle", "biwul": "biwul snake", "yirku-yirku": "yirku-yirku frog", "jadi": "jadi goanna", "walkarr": "walkarr goanna", "bajabaja": "bajabaja lizard"}
TARGET_GLOSSES = {"kalkamuku": "kalkamuku.snake", "karrkurr": "karrkurr.frog", "jinkalmu": "jinkalmu.snake", "barka": "barka.snake", "yalnga": "yalnga.turtle", "biwul": "biwul.snake", "yirku-yirku": "yirku-yirku.frog", "jadi": "jadi.goanna", "walkarr": "walkarr.goanna", "bajabaja": "bajabaja.lizard"}
TARGET_CONFIDENCE = {"kalkamuku": "0.90", "karrkurr": "0.91", "jinkalmu": "0.83", "barka": "0.80", "yalnga": "0.88", "biwul": "0.82", "yirku-yirku": "0.91", "jadi": "0.88", "walkarr": "0.90", "bajabaja": "0.85"}
EXPECTED_TARGET_COVERAGE = {"kalkamuku": 5, "karrkurr": 10, "jinkalmu": 11, "barka": 13, "yalnga": 13, "biwul": 14, "yirku-yirku": 14, "jadi": 18, "walkarr": 20, "bajabaja": 21}
EXPECTED_SUPPORT_COVERAGE = {"ngayu": 1461, "yundu": 1057, "nyulu": 732, "bula": 528, "jana": 1233, "yaluy": 4432, "yinyay": 4604, "nyajin": 2150}
FRAME_SPECS = [
    ("ngayu", "yaluy", "I saw", "here", "1sg"),
    ("yundu", "yinyay", "You saw", "there", "2sg"),
    ("nyulu", "yaluy", "He saw", "here", "3sg"),
    ("bula", "yinyay", "The two of them saw", "there", "3du"),
    ("jana", "yaluy", "They saw", "here", "3pl"),
]

DENY_KUKU = {"ngali", "ngaliny", "yubal", "yurra", "nganjin", "ngana", "yulu", "iana", "yirku", "baja", "yalay", "yala", "yanyu", "yinya", "nyajil", "nyaji-l", "nyaji-nka", "nyaji-l-nyaji", "milka", "baykal", "jalngkay"}
DENY_ENGLISH = ("green", "brown", "yellow", "black", "blue-tongue", "tree habitat", "water habitat", "sea habitat", "scrub habitat", "sand habitat", "taipan", "nut", "fruit", "july", "october", "mother-in-law", "avoidance language", "poison", "danger", "sac", "remove", "butcher", "eyes", "boys", "eat", "fierce", "fight", "bite", "kill", "old people", "taboo", "spring", "story", "place", "eggs", "hatch", "river", "rocks", "sound", "source", "possess", "event", "productive reduplication", "free base")


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}", TARGET_CONFIDENCE[target])


ROWS = [
    row(1, "I saw the kalkamuku snake here.", "Ngayu kalkamuku yaluy nyajin.", "ngayu kalkamuku yaluy nyajin | 1sg.NOM kalkamuku.snake here see.PST", "r342_1sg_here_reptile_c_saw_kalkamuku", ["ngayu", "kalkamuku", "yaluy", "nyajin"]),
    row(2, "I saw the karrkurr frog here.", "Ngayu karrkurr yaluy nyajin.", "ngayu karrkurr yaluy nyajin | 1sg.NOM karrkurr.frog here see.PST", "r342_1sg_here_reptile_c_saw_karrkurr", ["ngayu", "karrkurr", "yaluy", "nyajin"]),
    row(3, "I saw the jinkalmu snake here.", "Ngayu jinkalmu yaluy nyajin.", "ngayu jinkalmu yaluy nyajin | 1sg.NOM jinkalmu.snake here see.PST", "r342_1sg_here_reptile_c_saw_jinkalmu", ["ngayu", "jinkalmu", "yaluy", "nyajin"]),
    row(4, "I saw the barka snake here.", "Ngayu barka yaluy nyajin.", "ngayu barka yaluy nyajin | 1sg.NOM barka.snake here see.PST", "r342_1sg_here_reptile_c_saw_barka", ["ngayu", "barka", "yaluy", "nyajin"]),
    row(5, "I saw the yalnga turtle here.", "Ngayu yalnga yaluy nyajin.", "ngayu yalnga yaluy nyajin | 1sg.NOM yalnga.turtle here see.PST", "r342_1sg_here_reptile_c_saw_yalnga", ["ngayu", "yalnga", "yaluy", "nyajin"]),
    row(6, "I saw the biwul snake here.", "Ngayu biwul yaluy nyajin.", "ngayu biwul yaluy nyajin | 1sg.NOM biwul.snake here see.PST", "r342_1sg_here_reptile_c_saw_biwul", ["ngayu", "biwul", "yaluy", "nyajin"]),
    row(7, "I saw the yirku-yirku frog here.", "Ngayu yirku-yirku yaluy nyajin.", "ngayu yirku-yirku yaluy nyajin | 1sg.NOM yirku-yirku.frog here see.PST", "r342_1sg_here_reptile_c_saw_yirku_yirku", ["ngayu", "yirku-yirku", "yaluy", "nyajin"]),
    row(8, "I saw the jadi goanna here.", "Ngayu jadi yaluy nyajin.", "ngayu jadi yaluy nyajin | 1sg.NOM jadi.goanna here see.PST", "r342_1sg_here_reptile_c_saw_jadi", ["ngayu", "jadi", "yaluy", "nyajin"]),
    row(9, "I saw the walkarr goanna here.", "Ngayu walkarr yaluy nyajin.", "ngayu walkarr yaluy nyajin | 1sg.NOM walkarr.goanna here see.PST", "r342_1sg_here_reptile_c_saw_walkarr", ["ngayu", "walkarr", "yaluy", "nyajin"]),
    row(10, "I saw the bajabaja lizard here.", "Ngayu bajabaja yaluy nyajin.", "ngayu bajabaja yaluy nyajin | 1sg.NOM bajabaja.lizard here see.PST", "r342_1sg_here_reptile_c_saw_bajabaja", ["ngayu", "bajabaja", "yaluy", "nyajin"]),
    row(11, "You saw the kalkamuku snake there.", "Yundu kalkamuku yinyay nyajin.", "yundu kalkamuku yinyay nyajin | 2sg.NOM kalkamuku.snake there see.PST", "r342_2sg_there_reptile_c_saw_kalkamuku", ["yundu", "kalkamuku", "yinyay", "nyajin"]),
    row(12, "You saw the karrkurr frog there.", "Yundu karrkurr yinyay nyajin.", "yundu karrkurr yinyay nyajin | 2sg.NOM karrkurr.frog there see.PST", "r342_2sg_there_reptile_c_saw_karrkurr", ["yundu", "karrkurr", "yinyay", "nyajin"]),
    row(13, "You saw the jinkalmu snake there.", "Yundu jinkalmu yinyay nyajin.", "yundu jinkalmu yinyay nyajin | 2sg.NOM jinkalmu.snake there see.PST", "r342_2sg_there_reptile_c_saw_jinkalmu", ["yundu", "jinkalmu", "yinyay", "nyajin"]),
    row(14, "You saw the barka snake there.", "Yundu barka yinyay nyajin.", "yundu barka yinyay nyajin | 2sg.NOM barka.snake there see.PST", "r342_2sg_there_reptile_c_saw_barka", ["yundu", "barka", "yinyay", "nyajin"]),
    row(15, "You saw the yalnga turtle there.", "Yundu yalnga yinyay nyajin.", "yundu yalnga yinyay nyajin | 2sg.NOM yalnga.turtle there see.PST", "r342_2sg_there_reptile_c_saw_yalnga", ["yundu", "yalnga", "yinyay", "nyajin"]),
    row(16, "You saw the biwul snake there.", "Yundu biwul yinyay nyajin.", "yundu biwul yinyay nyajin | 2sg.NOM biwul.snake there see.PST", "r342_2sg_there_reptile_c_saw_biwul", ["yundu", "biwul", "yinyay", "nyajin"]),
    row(17, "You saw the yirku-yirku frog there.", "Yundu yirku-yirku yinyay nyajin.", "yundu yirku-yirku yinyay nyajin | 2sg.NOM yirku-yirku.frog there see.PST", "r342_2sg_there_reptile_c_saw_yirku_yirku", ["yundu", "yirku-yirku", "yinyay", "nyajin"]),
    row(18, "You saw the jadi goanna there.", "Yundu jadi yinyay nyajin.", "yundu jadi yinyay nyajin | 2sg.NOM jadi.goanna there see.PST", "r342_2sg_there_reptile_c_saw_jadi", ["yundu", "jadi", "yinyay", "nyajin"]),
    row(19, "You saw the walkarr goanna there.", "Yundu walkarr yinyay nyajin.", "yundu walkarr yinyay nyajin | 2sg.NOM walkarr.goanna there see.PST", "r342_2sg_there_reptile_c_saw_walkarr", ["yundu", "walkarr", "yinyay", "nyajin"]),
    row(20, "You saw the bajabaja lizard there.", "Yundu bajabaja yinyay nyajin.", "yundu bajabaja yinyay nyajin | 2sg.NOM bajabaja.lizard there see.PST", "r342_2sg_there_reptile_c_saw_bajabaja", ["yundu", "bajabaja", "yinyay", "nyajin"]),
    row(21, "He saw the kalkamuku snake here.", "Nyulu kalkamuku yaluy nyajin.", "nyulu kalkamuku yaluy nyajin | 3sg.NOM kalkamuku.snake here see.PST", "r342_3sg_here_reptile_c_saw_kalkamuku", ["nyulu", "kalkamuku", "yaluy", "nyajin"]),
    row(22, "He saw the karrkurr frog here.", "Nyulu karrkurr yaluy nyajin.", "nyulu karrkurr yaluy nyajin | 3sg.NOM karrkurr.frog here see.PST", "r342_3sg_here_reptile_c_saw_karrkurr", ["nyulu", "karrkurr", "yaluy", "nyajin"]),
    row(23, "He saw the jinkalmu snake here.", "Nyulu jinkalmu yaluy nyajin.", "nyulu jinkalmu yaluy nyajin | 3sg.NOM jinkalmu.snake here see.PST", "r342_3sg_here_reptile_c_saw_jinkalmu", ["nyulu", "jinkalmu", "yaluy", "nyajin"]),
    row(24, "He saw the barka snake here.", "Nyulu barka yaluy nyajin.", "nyulu barka yaluy nyajin | 3sg.NOM barka.snake here see.PST", "r342_3sg_here_reptile_c_saw_barka", ["nyulu", "barka", "yaluy", "nyajin"]),
    row(25, "He saw the yalnga turtle here.", "Nyulu yalnga yaluy nyajin.", "nyulu yalnga yaluy nyajin | 3sg.NOM yalnga.turtle here see.PST", "r342_3sg_here_reptile_c_saw_yalnga", ["nyulu", "yalnga", "yaluy", "nyajin"]),
    row(26, "He saw the biwul snake here.", "Nyulu biwul yaluy nyajin.", "nyulu biwul yaluy nyajin | 3sg.NOM biwul.snake here see.PST", "r342_3sg_here_reptile_c_saw_biwul", ["nyulu", "biwul", "yaluy", "nyajin"]),
    row(27, "He saw the yirku-yirku frog here.", "Nyulu yirku-yirku yaluy nyajin.", "nyulu yirku-yirku yaluy nyajin | 3sg.NOM yirku-yirku.frog here see.PST", "r342_3sg_here_reptile_c_saw_yirku_yirku", ["nyulu", "yirku-yirku", "yaluy", "nyajin"]),
    row(28, "He saw the jadi goanna here.", "Nyulu jadi yaluy nyajin.", "nyulu jadi yaluy nyajin | 3sg.NOM jadi.goanna here see.PST", "r342_3sg_here_reptile_c_saw_jadi", ["nyulu", "jadi", "yaluy", "nyajin"]),
    row(29, "He saw the walkarr goanna here.", "Nyulu walkarr yaluy nyajin.", "nyulu walkarr yaluy nyajin | 3sg.NOM walkarr.goanna here see.PST", "r342_3sg_here_reptile_c_saw_walkarr", ["nyulu", "walkarr", "yaluy", "nyajin"]),
    row(30, "He saw the bajabaja lizard here.", "Nyulu bajabaja yaluy nyajin.", "nyulu bajabaja yaluy nyajin | 3sg.NOM bajabaja.lizard here see.PST", "r342_3sg_here_reptile_c_saw_bajabaja", ["nyulu", "bajabaja", "yaluy", "nyajin"]),
    row(31, "The two of them saw the kalkamuku snake there.", "Bula kalkamuku yinyay nyajin.", "bula kalkamuku yinyay nyajin | 3du.NOM kalkamuku.snake there see.PST", "r342_3du_there_reptile_c_saw_kalkamuku", ["bula", "kalkamuku", "yinyay", "nyajin"]),
    row(32, "The two of them saw the karrkurr frog there.", "Bula karrkurr yinyay nyajin.", "bula karrkurr yinyay nyajin | 3du.NOM karrkurr.frog there see.PST", "r342_3du_there_reptile_c_saw_karrkurr", ["bula", "karrkurr", "yinyay", "nyajin"]),
    row(33, "The two of them saw the jinkalmu snake there.", "Bula jinkalmu yinyay nyajin.", "bula jinkalmu yinyay nyajin | 3du.NOM jinkalmu.snake there see.PST", "r342_3du_there_reptile_c_saw_jinkalmu", ["bula", "jinkalmu", "yinyay", "nyajin"]),
    row(34, "The two of them saw the barka snake there.", "Bula barka yinyay nyajin.", "bula barka yinyay nyajin | 3du.NOM barka.snake there see.PST", "r342_3du_there_reptile_c_saw_barka", ["bula", "barka", "yinyay", "nyajin"]),
    row(35, "The two of them saw the yalnga turtle there.", "Bula yalnga yinyay nyajin.", "bula yalnga yinyay nyajin | 3du.NOM yalnga.turtle there see.PST", "r342_3du_there_reptile_c_saw_yalnga", ["bula", "yalnga", "yinyay", "nyajin"]),
    row(36, "The two of them saw the biwul snake there.", "Bula biwul yinyay nyajin.", "bula biwul yinyay nyajin | 3du.NOM biwul.snake there see.PST", "r342_3du_there_reptile_c_saw_biwul", ["bula", "biwul", "yinyay", "nyajin"]),
    row(37, "The two of them saw the yirku-yirku frog there.", "Bula yirku-yirku yinyay nyajin.", "bula yirku-yirku yinyay nyajin | 3du.NOM yirku-yirku.frog there see.PST", "r342_3du_there_reptile_c_saw_yirku_yirku", ["bula", "yirku-yirku", "yinyay", "nyajin"]),
    row(38, "The two of them saw the jadi goanna there.", "Bula jadi yinyay nyajin.", "bula jadi yinyay nyajin | 3du.NOM jadi.goanna there see.PST", "r342_3du_there_reptile_c_saw_jadi", ["bula", "jadi", "yinyay", "nyajin"]),
    row(39, "The two of them saw the walkarr goanna there.", "Bula walkarr yinyay nyajin.", "bula walkarr yinyay nyajin | 3du.NOM walkarr.goanna there see.PST", "r342_3du_there_reptile_c_saw_walkarr", ["bula", "walkarr", "yinyay", "nyajin"]),
    row(40, "The two of them saw the bajabaja lizard there.", "Bula bajabaja yinyay nyajin.", "bula bajabaja yinyay nyajin | 3du.NOM bajabaja.lizard there see.PST", "r342_3du_there_reptile_c_saw_bajabaja", ["bula", "bajabaja", "yinyay", "nyajin"]),
    row(41, "They saw the kalkamuku snake here.", "Jana kalkamuku yaluy nyajin.", "jana kalkamuku yaluy nyajin | 3pl.NOM kalkamuku.snake here see.PST", "r342_3pl_here_reptile_c_saw_kalkamuku", ["jana", "kalkamuku", "yaluy", "nyajin"]),
    row(42, "They saw the karrkurr frog here.", "Jana karrkurr yaluy nyajin.", "jana karrkurr yaluy nyajin | 3pl.NOM karrkurr.frog here see.PST", "r342_3pl_here_reptile_c_saw_karrkurr", ["jana", "karrkurr", "yaluy", "nyajin"]),
    row(43, "They saw the jinkalmu snake here.", "Jana jinkalmu yaluy nyajin.", "jana jinkalmu yaluy nyajin | 3pl.NOM jinkalmu.snake here see.PST", "r342_3pl_here_reptile_c_saw_jinkalmu", ["jana", "jinkalmu", "yaluy", "nyajin"]),
    row(44, "They saw the barka snake here.", "Jana barka yaluy nyajin.", "jana barka yaluy nyajin | 3pl.NOM barka.snake here see.PST", "r342_3pl_here_reptile_c_saw_barka", ["jana", "barka", "yaluy", "nyajin"]),
    row(45, "They saw the yalnga turtle here.", "Jana yalnga yaluy nyajin.", "jana yalnga yaluy nyajin | 3pl.NOM yalnga.turtle here see.PST", "r342_3pl_here_reptile_c_saw_yalnga", ["jana", "yalnga", "yaluy", "nyajin"]),
    row(46, "They saw the biwul snake here.", "Jana biwul yaluy nyajin.", "jana biwul yaluy nyajin | 3pl.NOM biwul.snake here see.PST", "r342_3pl_here_reptile_c_saw_biwul", ["jana", "biwul", "yaluy", "nyajin"]),
    row(47, "They saw the yirku-yirku frog here.", "Jana yirku-yirku yaluy nyajin.", "jana yirku-yirku yaluy nyajin | 3pl.NOM yirku-yirku.frog here see.PST", "r342_3pl_here_reptile_c_saw_yirku_yirku", ["jana", "yirku-yirku", "yaluy", "nyajin"]),
    row(48, "They saw the jadi goanna here.", "Jana jadi yaluy nyajin.", "jana jadi yaluy nyajin | 3pl.NOM jadi.goanna here see.PST", "r342_3pl_here_reptile_c_saw_jadi", ["jana", "jadi", "yaluy", "nyajin"]),
    row(49, "They saw the walkarr goanna here.", "Jana walkarr yaluy nyajin.", "jana walkarr yaluy nyajin | 3pl.NOM walkarr.goanna here see.PST", "r342_3pl_here_reptile_c_saw_walkarr", ["jana", "walkarr", "yaluy", "nyajin"]),
    row(50, "They saw the bajabaja lizard here.", "Jana bajabaja yaluy nyajin.", "jana bajabaja yaluy nyajin | 3pl.NOM bajabaja.lizard here see.PST", "r342_3pl_here_reptile_c_saw_bajabaja", ["jana", "bajabaja", "yaluy", "nyajin"]),
]


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[1] for r in ROWS}) != 50: issues.append("duplicate English surface")
    if len({r[2] for r in ROWS}) != 50: issues.append("duplicate Kuku surface")
    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,prefix,location,person=FRAME_SPECS[band]
        ek=f"{pronoun.capitalize()} {target} {demo} nyajin."; ee=f"{prefix} the {TARGET_LABELS[target]} {location}."; ea=f"{pronoun} {target} {demo} nyajin | {person}.NOM {TARGET_GLOSSES[target]} {location} see.PST"
        if loans: issues.append(f"{seq}: loans {loans}")
        denied=sorted({w for w in DENY_KUKU if re.search(rf"(^|\s){re.escape(w)}([\s\.]|$)",kuku.lower())})
        if denied: issues.append(f"{seq}: denied Kuku {denied}")
        de=[x for x in DENY_ENGLISH if re.search(rf"\b{re.escape(x)}\b",english.lower())]
        if de: issues.append(f"{seq}: English drift {de}")
        if kuku!=ek: issues.append(f"{seq}: Kuku mismatch")
        if english!=ee: issues.append(f"{seq}: English mismatch")
        if analysis!=ea: issues.append(f"{seq}: analysis mismatch")
        if words!=[pronoun,target,demo,"nyajin"]: issues.append(f"{seq}: words mismatch")
        if kuku.lower().rstrip(".")!=" ".join(words): issues.append(f"{seq}: surface/words mismatch")
        if not frame.startswith("r342_"): issues.append(f"{seq}: frame mismatch")
        if TARGET_EVIDENCE[target] not in evidence or SUPPORT_EVIDENCE not in evidence: issues.append(f"{seq}: evidence mismatch")
        if confidence!=TARGET_CONFIDENCE[target]: issues.append(f"{seq}: confidence mismatch")
    return issues


def main() -> int:
    issues=scan_static()
    if issues: print("\n".join(issues)); 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} exists")
    tc=count_words(db,TARGET_ORDER); sc=count_words(db,list(EXPECTED_SUPPORT_COVERAGE))
    if tc!=EXPECTED_TARGET_COVERAGE: raise SystemExit(f"target coverage changed: {tc}")
    if sc!=EXPECTED_SUPPORT_COVERAGE: raise SystemExit(f"support coverage changed: {sc}")
    grid=[]
    for p in ["ngayu","yundu","nyulu","bula","jana"]:
        for de in ["yaluy","yinyay"]:
            for t in TARGET_ORDER:
                surf=f"{p.capitalize()} {t} {de} nyajin."
                hits=db.execute("SELECT b.label,s.seq FROM sentences s JOIN batches b ON b.id=s.batch_id WHERE lower(s.kuku)=lower(?) AND s.status!='rejected' ORDER BY b.label,s.seq",(surf,)).fetchall()
                if hits: grid.append((surf,hits))
    if grid: raise SystemExit(f"construction grid changed: {grid}")
    inverse=[]
    for p,de in [("ngayu","yinyay"),("yundu","yaluy"),("nyulu","yinyay"),("bula","yaluy"),("jana","yinyay")]:
        for t in TARGET_ORDER:
            surf=f"{p.capitalize()} {t} {de} nyajin."
            hits=db.execute("SELECT b.label,s.seq FROM sentences s JOIN batches b ON b.id=s.batch_id WHERE lower(s.kuku)=lower(?) AND s.status!='rejected' ORDER BY b.label,s.seq",(surf,)).fetchall()
            if hits: inverse.append((surf,hits))
    if inverse: raise SystemExit(f"inverse collisions: {inverse}")
    verified,words=db.execute("SELECT COUNT(*),SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1) FROM sentences WHERE status IN ('accepted','revised')").fetchone()
    if (verified,words)!=(19247,132347): raise SystemExit(f"baseline changed {verified}/{words}")
    notes=("SENSE-QUALIFIED REPTILE LEXEME-SET-C SINGULAR/THIRD PAST PERCEPTION AFTER RULE 341 (Rule 342). 50 under-review rows over kalkamuku, karrkurr, jinkalmu, barka, yalnga, biwul, yirku-yirku, jadi, walkarr, and bajabaja. Raw coverage 5-21 overstates barka snake and biwul snake sense coverage. Duplicate records, polysemy/homonymy, taxonomic ambiguity, kinship/avoidance, nut/flora, food taboo/safety, myth/place/story, whole reduplicated heads, colour/body/habitat, source case/events remain closed. Full 100-cell grid empty; both orientations collision-free; selected gap 172->162.")
    cur=db.execute("INSERT INTO batches(label,cheatsheet_version,guide_version,notes,created_at) VALUES(?,?,?,?,?)",(LABEL,"Rule 342 under review","operator-guide-2026-07-10",notes,NOW));bid=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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[(bid,seq,en,ku,an,fr,ti,wo,lo,ev,"under_review",co,"project_approved_synthetic_pending_elder_verification","codex-main",NOW,NOW) for seq,en,ku,an,fr,ti,wo,lo,ev,co in ROWS])
    events=[
        ("source","source-readback","Reread all exact set-C records; barka nut/snake and biwul kin/snake polysemy; jinkalmu taxonomic/cultural records; bajabaja myth/place record; Patz target contexts; singular/third pronouns, locals, past/perception, and dictionary nyajin."),
        ("planning","record-sense-audit","Recorded kalkamuku/jinkalmu duplicates; barka and biwul polysemy; jinkalmu species/cultural ambiguity; yalnga food-safety; jadi taboo; bajabaja myth/place; whole yirku-yirku/bajabaja; and all property/habitat/source-event exclusions."),
        ("planning","construction-gap-audit","Exact singular/third-pronoun x ten-target x two-deictic matrix found all 100 past surfaces empty; both 50-row orientations internally unique and collision-free."),
        ("planning","deictic-balance-audit","Before banking yaluy=4432 and yinyay=4604, gap 172; selected three-here/two-there projects 162; inverse projects 182."),
        ("preflight","coverage-audit",f"Coverage before banking: targets={tc}; support={sc}."),
        ("preflight","duplicate-preflight","Selected and inverse 50-row surfaces are internally unique and collision-free; complete 100-cell grid is empty."),
        ("preflight","static-guard-pass","50 explicit singular/third rows; conservative sense-qualified labels; no duplicate/polysemy/taxonomy/kinship/flora/taboo/safety/myth/place/component/property/habitat/source-event, loan, case, or support drift."),
    ]
    for phase,etype,detail in events: record_event(db,batch_label=LABEL,phase=phase,event_type=etype,actor="codex",detail=detail,artifact_path=PROCESS_LOG,created_at=NOW)
    record_event(db,batch_label=LABEL,phase="bank",event_type="bank-success",actor="codex",detail=f"Banked 50 Rule 342 rows under_review; verified remains {verified}; words {words}.",command="python3 batch_scripts/bank_384.py",output_excerpt="50 under_review",artifact_path=PROCESS_LOG,created_at=NOW)
    db.commit();print("banked batch-384: 50 rows under_review");return 0


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




