#!/usr/bin/env python3
"""Bank batch-188: Rule 146 construction consolidation after Rule 145."""

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-188"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-188-construction-consolidation-after-rule145-process.md"

TARGET_HEADS = {
    "kuyu": "fish",
    "ngawiya": "sea.turtle",
    "ngujay": "freshwater.turtle",
    "bilngkumu": "saltwater.crocodile",
    "kubarr": "freshwater.eel",
    "yawu": "stingray",
    "yaburr": "shark",
    "kiju": "mud.crab",
    "ngalngal": "sand.crab",
}
SUPPORT_FORMS = {"bana-nga"}
DENY = {
    "ngiwa", "diwan", "wabul", "wakuka", "jarruka", "dikal", "kurranji", "nili-nili", "kalbu", "dulku",
    "birrbirr", "jamarbina", "bajar", "mili", "ngalku", "babajaka", "baril-baril", "baway", "bilar", "kabal",
    "yalngkal", "yumu", "jimal", "ngunjil", "dumbul", "buyku", "jikan", "baya", "kubu", "nganjirr",
}
PRONOUN_A = {"ngayu", "ngana", "jana"}
COMMON_A = {"ngamu-ngku", "nganjan-angka", "babi-ngka", "karrkay-ngku", "kami-ngka", "jalbu-ngku", "dingkar-angka"}
DENIED_ENGLISH = (
    "catch", "caught", "catching", "spear", "speared", "spearing", "hook", "hooked", "net", "netting",
    "cook", "cooked", "cooking", "roast", "roasted", "stew", "stewed", "eat", "eating", "meat", "food",
    "taboo", "storm", "rain", "fear", "afraid", "bite", "biting", "ill", "sick", "sickness", "story",
    "myth", "totem", "dream",
)


def js(values: list[str]) -> str:
    return json.dumps(values, ensure_ascii=False)


ROWS = [
    (1, "Mother saw the sea turtle.", "Ngamu-ngku ngawiya nyajin.",
     "ngamu-ngku ngawiya nyaji-ny | mother-ERG sea.turtle see-PAST", "r146_perception_mother_sea_turtle", 4, js(["ngamu", "ngawiya", "nyaji-l"]), js([]),
     "Construction consolidation: common-noun A ERG; ngawiya sea turtle object.", "0.84"),
    (2, "Father saw the freshwater turtle.", "Nganjan-angka ngujay nyajin.",
     "nganjan-angka ngujay nyaji-ny | father-ERG freshwater.turtle see-PAST", "r146_perception_father_freshwater_turtle", 4, js(["nganjan", "ngujay", "nyaji-l"]), js([]),
     "Common-noun A ERG; ngujay freshwater turtle object.", "0.84"),
    (3, "Grandmother saw the saltwater crocodile.", "Babi-ngka bilngkumu nyajin.",
     "babi-ngka bilngkumu nyaji-ny | grandmother-ERG saltwater.crocodile see-PAST", "r146_perception_grandmother_crocodile", 4, js(["babi", "bilngkumu", "nyaji-l"]), js([]),
     "Bilngkumu saltwater crocodile only; no fear/story row.", "0.84"),
    (4, "The child saw the freshwater eel.", "Karrkay-ngku kubarr nyajin.",
     "karrkay-ngku kubarr nyaji-ny | child-ERG freshwater.eel see-PAST", "r146_perception_child_eel", 4, js(["karrkay", "kubarr", "nyaji-l"]), js([]),
     "Kubarr freshwater eel object; no cooking/eating row.", "0.84"),
    (5, "Grandfather saw the stingray.", "Kami-ngka yawu nyajin.",
     "kami-ngka yawu nyaji-ny | grandfather-ERG stingray see-PAST", "r146_perception_grandfather_stingray", 4, js(["kami", "yawu", "nyaji-l"]), js([]),
     "Yawu stingray only; no storm/spearing row.", "0.84"),
    (6, "The woman saw the shark.", "Jalbu-ngku yaburr nyajin.",
     "jalbu-ngku yaburr nyaji-ny | woman-ERG shark see-PAST", "r146_perception_woman_shark", 4, js(["jalbu", "yaburr", "nyaji-l"]), js([]),
     "Yaburr shark object; no biting row.", "0.84"),
    (7, "The man saw the mud crab.", "Dingkar-angka kiju nyajin.",
     "dingkar-angka kiju nyaji-ny | man-ERG mud.crab see-PAST", "r146_perception_man_mud_crab", 4, js(["dingkar", "kiju", "nyaji-l"]), js([]),
     "Kiju mud crab object; no fear/nip row.", "0.84"),
    (8, "I saw the sand crab.", "Ngayu ngalngal nyajin.",
     "ngayu ngalngal nyaji-ny | I sand.crab see-PAST", "r146_perception_i_sand_crab", 4, js(["ngayu", "ngalngal", "nyaji-l"]), js([]),
     "Pronoun A bare; ngalngal whole sand-crab head.", "0.84"),
    (9, "We saw the fish.", "Ngana kuyu nyajin.",
     "ngana kuyu nyaji-ny | we fish see-PAST", "r146_perception_we_fish", 4, js(["ngana", "kuyu", "nyaji-l"]), js([]),
     "Pronoun A bare; kuyu fish object.", "0.84"),
    (10, "They saw the sea turtle.", "Jana ngawiya nyajin.",
     "jana ngawiya nyaji-ny | they sea.turtle see-PAST", "r146_perception_they_sea_turtle", 4, js(["jana", "ngawiya", "nyaji-l"]), js([]),
     "Pronoun A bare; ngawiya sea turtle object.", "0.84"),
    (11, "Mother saw the freshwater turtle.", "Ngamu-ngku ngujay nyajin.",
     "ngamu-ngku ngujay nyaji-ny | mother-ERG freshwater.turtle see-PAST", "r146_perception_mother_freshwater_turtle", 4, js(["ngamu", "ngujay", "nyaji-l"]), js([]),
     "Common-noun A ERG; ngujay object.", "0.84"),
    (12, "Father saw the saltwater crocodile.", "Nganjan-angka bilngkumu nyajin.",
     "nganjan-angka bilngkumu nyaji-ny | father-ERG saltwater.crocodile see-PAST", "r146_perception_father_crocodile", 4, js(["nganjan", "bilngkumu", "nyaji-l"]), js([]),
     "Bilngkumu saltwater crocodile; no story/fear row.", "0.84"),
    (13, "Grandmother saw the freshwater eel.", "Babi-ngka kubarr nyajin.",
     "babi-ngka kubarr nyaji-ny | grandmother-ERG freshwater.eel see-PAST", "r146_perception_grandmother_eel", 4, js(["babi", "kubarr", "nyaji-l"]), js([]),
     "Kubarr eel object; no sickness/eating row.", "0.84"),
    (14, "The child saw the stingray.", "Karrkay-ngku yawu nyajin.",
     "karrkay-ngku yawu nyaji-ny | child-ERG stingray see-PAST", "r146_perception_child_stingray", 4, js(["karrkay", "yawu", "nyaji-l"]), js([]),
     "Yawu stingray object; no storm row.", "0.84"),
    (15, "Grandfather saw the shark.", "Kami-ngka yaburr nyajin.",
     "kami-ngka yaburr nyaji-ny | grandfather-ERG shark see-PAST", "r146_perception_grandfather_shark", 4, js(["kami", "yaburr", "nyaji-l"]), js([]),
     "Yaburr shark object; no biting row.", "0.84"),
    (16, "The woman saw the mud crab.", "Jalbu-ngku kiju nyajin.",
     "jalbu-ngku kiju nyaji-ny | woman-ERG mud.crab see-PAST", "r146_perception_woman_mud_crab", 4, js(["jalbu", "kiju", "nyaji-l"]), js([]),
     "Kiju mud crab object.", "0.84"),
    (17, "The man saw the sand crab.", "Dingkar-angka ngalngal nyajin.",
     "dingkar-angka ngalngal nyaji-ny | man-ERG sand.crab see-PAST", "r146_perception_man_sand_crab", 4, js(["dingkar", "ngalngal", "nyaji-l"]), js([]),
     "Ngalngal sand crab whole head.", "0.84"),
    (18, "I saw the sea turtle.", "Ngayu ngawiya nyajin.",
     "ngayu ngawiya nyaji-ny | I sea.turtle see-PAST", "r146_perception_i_sea_turtle", 4, js(["ngayu", "ngawiya", "nyaji-l"]), js([]),
     "Pronoun A bare; sea turtle object.", "0.84"),
    (19, "We saw the saltwater crocodile.", "Ngana bilngkumu nyajin.",
     "ngana bilngkumu nyaji-ny | we saltwater.crocodile see-PAST", "r146_perception_we_crocodile", 4, js(["ngana", "bilngkumu", "nyaji-l"]), js([]),
     "Pronoun A bare; bilngkumu object.", "0.84"),
    (20, "They saw the freshwater eel.", "Jana kubarr nyajin.",
     "jana kubarr nyaji-ny | they freshwater.eel see-PAST", "r146_perception_they_eel", 4, js(["jana", "kubarr", "nyaji-l"]), js([]),
     "Pronoun A bare; kubarr object.", "0.84"),

    (21, "Mother saw the sea turtle in the water.", "Ngamu-ngku ngawiya bana-nga nyajin.",
     "ngamu-ngku ngawiya bana-nga nyaji-ny | mother-ERG sea.turtle water-LOC see-PAST", "r146_perception_mother_sea_turtle_water", 4, js(["ngamu", "ngawiya", "bana", "nyaji-l"]), js([]),
     "Common-noun A ERG; bana-nga support location.", "0.84"),
    (22, "Father saw the freshwater turtle in the water.", "Nganjan-angka ngujay bana-nga nyajin.",
     "nganjan-angka ngujay bana-nga nyaji-ny | father-ERG freshwater.turtle water-LOC see-PAST", "r146_perception_father_freshwater_turtle_water", 4, js(["nganjan", "ngujay", "bana", "nyaji-l"]), js([]),
     "Ngujay object with water LOC.", "0.84"),
    (23, "Grandmother saw the saltwater crocodile in the water.", "Babi-ngka bilngkumu bana-nga nyajin.",
     "babi-ngka bilngkumu bana-nga nyaji-ny | grandmother-ERG saltwater.crocodile water-LOC see-PAST", "r146_perception_grandmother_crocodile_water", 4, js(["babi", "bilngkumu", "bana", "nyaji-l"]), js([]),
     "Bilngkumu object with water LOC; no fear/story row.", "0.84"),
    (24, "The child saw the freshwater eel in the water.", "Karrkay-ngku kubarr bana-nga nyajin.",
     "karrkay-ngku kubarr bana-nga nyaji-ny | child-ERG freshwater.eel water-LOC see-PAST", "r146_perception_child_eel_water", 4, js(["karrkay", "kubarr", "bana", "nyaji-l"]), js([]),
     "Kubarr eel object with water LOC.", "0.84"),
    (25, "Grandfather saw the stingray in the water.", "Kami-ngka yawu bana-nga nyajin.",
     "kami-ngka yawu bana-nga nyaji-ny | grandfather-ERG stingray water-LOC see-PAST", "r146_perception_grandfather_stingray_water", 4, js(["kami", "yawu", "bana", "nyaji-l"]), js([]),
     "Yawu object with water LOC; no storm/spearing row.", "0.84"),
    (26, "The woman saw the shark in the water.", "Jalbu-ngku yaburr bana-nga nyajin.",
     "jalbu-ngku yaburr bana-nga nyaji-ny | woman-ERG shark water-LOC see-PAST", "r146_perception_woman_shark_water", 4, js(["jalbu", "yaburr", "bana", "nyaji-l"]), js([]),
     "Yaburr object with water LOC.", "0.84"),
    (27, "The man saw the mud crab in the water.", "Dingkar-angka kiju bana-nga nyajin.",
     "dingkar-angka kiju bana-nga nyaji-ny | man-ERG mud.crab water-LOC see-PAST", "r146_perception_man_mud_crab_water", 4, js(["dingkar", "kiju", "bana", "nyaji-l"]), js([]),
     "Kiju object with water LOC.", "0.84"),
    (28, "I saw the sand crab in the water.", "Ngayu ngalngal bana-nga nyajin.",
     "ngayu ngalngal bana-nga nyaji-ny | I sand.crab water-LOC see-PAST", "r146_perception_i_sand_crab_water", 4, js(["ngayu", "ngalngal", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; ngalngal with water support.", "0.84"),
    (29, "We saw the fish in the water.", "Ngana kuyu bana-nga nyajin.",
     "ngana kuyu bana-nga nyaji-ny | we fish water-LOC see-PAST", "r146_perception_we_fish_water", 4, js(["ngana", "kuyu", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; kuyu with water LOC.", "0.84"),
    (30, "They saw the sea turtle in the water.", "Jana ngawiya bana-nga nyajin.",
     "jana ngawiya bana-nga nyaji-ny | they sea.turtle water-LOC see-PAST", "r146_perception_they_sea_turtle_water", 4, js(["jana", "ngawiya", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; sea turtle with water LOC.", "0.84"),
    (31, "Mother saw the freshwater turtle in the water.", "Ngamu-ngku ngujay bana-nga nyajin.",
     "ngamu-ngku ngujay bana-nga nyaji-ny | mother-ERG freshwater.turtle water-LOC see-PAST", "r146_perception_mother_freshwater_turtle_water", 4, js(["ngamu", "ngujay", "bana", "nyaji-l"]), js([]),
     "Common-noun A ERG; ngujay object with water LOC.", "0.84"),
    (32, "Father saw the saltwater crocodile in the water.", "Nganjan-angka bilngkumu bana-nga nyajin.",
     "nganjan-angka bilngkumu bana-nga nyaji-ny | father-ERG saltwater.crocodile water-LOC see-PAST", "r146_perception_father_crocodile_water", 4, js(["nganjan", "bilngkumu", "bana", "nyaji-l"]), js([]),
     "Bilngkumu water-location perception; no fear/biting row.", "0.84"),
    (33, "Grandmother saw the freshwater eel in the water.", "Babi-ngka kubarr bana-nga nyajin.",
     "babi-ngka kubarr bana-nga nyaji-ny | grandmother-ERG freshwater.eel water-LOC see-PAST", "r146_perception_grandmother_eel_water", 4, js(["babi", "kubarr", "bana", "nyaji-l"]), js([]),
     "Kubarr water-location perception; no cooking/eating row.", "0.84"),
    (34, "The child saw the stingray in the water.", "Karrkay-ngku yawu bana-nga nyajin.",
     "karrkay-ngku yawu bana-nga nyaji-ny | child-ERG stingray water-LOC see-PAST", "r146_perception_child_stingray_water", 4, js(["karrkay", "yawu", "bana", "nyaji-l"]), js([]),
     "Yawu water-location perception; no storm/spearing row.", "0.84"),
    (35, "Grandfather saw the shark in the water.", "Kami-ngka yaburr bana-nga nyajin.",
     "kami-ngka yaburr bana-nga nyaji-ny | grandfather-ERG shark water-LOC see-PAST", "r146_perception_grandfather_shark_water", 4, js(["kami", "yaburr", "bana", "nyaji-l"]), js([]),
     "Yaburr with water LOC; no biting row.", "0.84"),
    (36, "The woman saw the mud crab in the water.", "Jalbu-ngku kiju bana-nga nyajin.",
     "jalbu-ngku kiju bana-nga nyaji-ny | woman-ERG mud.crab water-LOC see-PAST", "r146_perception_woman_mud_crab_water", 4, js(["jalbu", "kiju", "bana", "nyaji-l"]), js([]),
     "Kiju with water LOC.", "0.84"),
    (37, "The man saw the sand crab in the water.", "Dingkar-angka ngalngal bana-nga nyajin.",
     "dingkar-angka ngalngal bana-nga nyaji-ny | man-ERG sand.crab water-LOC see-PAST", "r146_perception_man_sand_crab_water", 4, js(["dingkar", "ngalngal", "bana", "nyaji-l"]), js([]),
     "Ngalngal whole head with water LOC.", "0.84"),
    (38, "I saw the sea turtle in the water.", "Ngayu ngawiya bana-nga nyajin.",
     "ngayu ngawiya bana-nga nyaji-ny | I sea.turtle water-LOC see-PAST", "r146_perception_i_sea_turtle_water", 4, js(["ngayu", "ngawiya", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; sea turtle with water LOC.", "0.84"),
    (39, "We saw the saltwater crocodile in the water.", "Ngana bilngkumu bana-nga nyajin.",
     "ngana bilngkumu bana-nga nyaji-ny | we saltwater.crocodile water-LOC see-PAST", "r146_perception_we_crocodile_water", 4, js(["ngana", "bilngkumu", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; bilngkumu with water LOC.", "0.84"),
    (40, "They saw the freshwater eel in the water.", "Jana kubarr bana-nga nyajin.",
     "jana kubarr bana-nga nyaji-ny | they freshwater.eel water-LOC see-PAST", "r146_perception_they_eel_water", 4, js(["jana", "kubarr", "bana", "nyaji-l"]), js([]),
     "Pronoun A bare; kubarr with water LOC.", "0.84"),

    (41, "I see the mud crab.", "Ngayu kiju nyajil.",
     "ngayu kiju nyaji-l | I mud.crab see-NONPAST", "r146_present_i_mud_crab", 4, js(["ngayu", "kiju", "nyaji-l"]), js([]),
     "Nyaji-l nonpast perception construction; pronoun A bare.", "0.84"),
    (42, "We see the sand crab.", "Ngana ngalngal nyajil.",
     "ngana ngalngal nyaji-l | we sand.crab see-NONPAST", "r146_present_we_sand_crab", 4, js(["ngana", "ngalngal", "nyaji-l"]), js([]),
     "Ngalngal whole head in present perception frame.", "0.84"),
    (43, "They see the fish.", "Jana kuyu nyajil.",
     "jana kuyu nyaji-l | they fish see-NONPAST", "r146_present_they_fish", 4, js(["jana", "kuyu", "nyaji-l"]), js([]),
     "Kuyu fish in present perception frame.", "0.84"),
    (44, "Mother sees the fish.", "Ngamu-ngku kuyu nyajil.",
     "ngamu-ngku kuyu nyaji-l | mother-ERG fish see-NONPAST", "r146_present_mother_fish", 4, js(["ngamu", "kuyu", "nyaji-l"]), js([]),
     "Common-noun A ERG in present perception frame.", "0.84"),
    (45, "Father sees the sea turtle.", "Nganjan-angka ngawiya nyajil.",
     "nganjan-angka ngawiya nyaji-l | father-ERG sea.turtle see-NONPAST", "r146_present_father_sea_turtle", 4, js(["nganjan", "ngawiya", "nyaji-l"]), js([]),
     "Common-noun A ERG; sea turtle object.", "0.84"),
    (46, "Grandmother sees the freshwater turtle.", "Babi-ngka ngujay nyajil.",
     "babi-ngka ngujay nyaji-l | grandmother-ERG freshwater.turtle see-NONPAST", "r146_present_grandmother_freshwater_turtle", 4, js(["babi", "ngujay", "nyaji-l"]), js([]),
     "Common-noun A ERG; freshwater turtle object.", "0.84"),
    (47, "The child sees the saltwater crocodile.", "Karrkay-ngku bilngkumu nyajil.",
     "karrkay-ngku bilngkumu nyaji-l | child-ERG saltwater.crocodile see-NONPAST", "r146_present_child_crocodile", 4, js(["karrkay", "bilngkumu", "nyaji-l"]), js([]),
     "Common-noun A ERG; bilngkumu object.", "0.84"),
    (48, "Grandfather sees the freshwater eel.", "Kami-ngka kubarr nyajil.",
     "kami-ngka kubarr nyaji-l | grandfather-ERG freshwater.eel see-NONPAST", "r146_present_grandfather_eel", 4, js(["kami", "kubarr", "nyaji-l"]), js([]),
     "Common-noun A ERG; kubarr object.", "0.84"),
    (49, "The woman sees the stingray.", "Jalbu-ngku yawu nyajil.",
     "jalbu-ngku yawu nyaji-l | woman-ERG stingray see-NONPAST", "r146_present_woman_stingray", 4, js(["jalbu", "yawu", "nyaji-l"]), js([]),
     "Common-noun A ERG; yawu object.", "0.84"),
    (50, "The man sees the shark.", "Dingkar-angka yaburr nyajil.",
     "dingkar-angka yaburr nyaji-l | man-ERG shark see-NONPAST", "r146_present_man_shark", 4, js(["dingkar", "yaburr", "nyaji-l"]), js([]),
     "Common-noun A ERG; yaburr object.", "0.84"),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", low) is not None


def first_word(low: str) -> str:
    return low.split()[0].strip(".,!?;:\"")


def has_target_case(low: str, head: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:ngka|ngku|angka|nga|ngu|ba|muny|bu|ji|jirr|ku|mundu|amu|mu)\b", 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_ku: set[str] = set()
    for expected, row in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        loans = json.loads(loans_used)
        if seq != expected:
            issues.append(f"{label}: sequence mismatch; expected {expected}")
        if not english[:1].isupper() or english[-1:] not in ".!?":
            issues.append(f"{label}: English punctuation/capitalization failure")
        if " | " not in analysis:
            issues.append(f"{label}: analysis missing gloss separator")
        if not frame.startswith("r146_"):
            issues.append(f"{label}: Rule 146 frame must start with r146_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        if loans:
            issues.append(f"{label}: no loan rows in this batch")
        for denied in DENY:
            if has_token(low, denied):
                issues.append(f"{label}: denied or out-of-scope token {denied!r}")
        targets = [head for head in TARGET_HEADS if has_token(low, head)]
        if len(targets) != 1:
            issues.append(f"{label}: expected exactly one Rule 146 target head, found {targets}")
        for head in targets:
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if TARGET_HEADS[head] not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {TARGET_HEADS[head]}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        for form in re.findall(r"\b[a-z]+-(?:nga|ba|muny|ngu)\b", low):
            if form not in SUPPORT_FORMS:
                issues.append(f"{label}: unapproved support local form {form}")
        if has_token(low, "bana-nga") and "bana" not in words:
            issues.append(f"{label}: support head bana missing from words_used")
        if has_token(low, "bilngkumu") and ("crocodile" not in english_low or "saltwater" not in english_low):
            issues.append(f"{label}: bilngkumu must be saltwater crocodile")
        if has_token(low, "ngawiya") and "sea turtle" not in english_low:
            issues.append(f"{label}: ngawiya must be sea turtle")
        if has_token(low, "ngujay") and "freshwater turtle" not in english_low:
            issues.append(f"{label}: ngujay must be freshwater turtle")
        if has_token(low, "kubarr") and ("eel" not in english_low or "freshwater" not in english_low):
            issues.append(f"{label}: kubarr must be freshwater eel")
        if has_token(low, "kiju") and "mud crab" not in english_low:
            issues.append(f"{label}: kiju must be mud crab")
        if has_token(low, "ngalngal") and "sand crab" not in english_low:
            issues.append(f"{label}: ngalngal must be sand crab")
        if "-bu" in low or "INST" in analysis:
            issues.append(f"{label}: no instrument morphology in Rule 146")
        if any(bad in english_low for bad in DENIED_ENGLISH):
            issues.append(f"{label}: denied fishing/food/storm/fear/story field in English")
        if "nyajin" in low or "nyajil" in low:
            first = first_word(low)
            if first not in PRONOUN_A and first not in COMMON_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun or ERG-marked common noun")
        if "nyajil" in low and "see-NONPAST" not in analysis:
            issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        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 sentences WHERE batch_id=?", (batch_id,))
        db.execute("UPDATE batches SET notes=?, created_at=? WHERE id=?", ("rebanked under_review", NOW, batch_id))
    else:
        cur = db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 146 draft: construction consolidation after Rule 145", "operator-guide-2026-07-07", "under_review", NOW),
        )
        batch_id = cur.lastrowid

    dupes: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        hit = db.execute(
            """
            SELECT b.label, s.seq
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(trim(s.kuku))=lower(trim(?))
              AND s.status!='rejected'
              AND s.batch_id!=?
            """,
            (kuku, batch_id),
        ).fetchone()
        if hit:
            dupes.append(f"{LABEL}.{seq:02d} duplicates {hit[0]}.{hit[1]:02d}: {kuku}")
    if dupes:
        db.rollback()
        print("cross-corpus duplicate check failed:")
        for dupe in dupes:
            print(f"  - {dupe}")
        return 1

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail=(
            "Rule 146 source pass admitted no new target heads. It retained the Rule 145 water-fauna names and "
            "source-checked perception support: bana-nga water LOC, nyaji-ny past, and nyaji-l nonpast."
        ),
        command="dictionary.yaml structured readback; grammar.md water-fauna and nyaji-l examples; sqlite lexeme and duplicate readback",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail=(
            "Rule 146 consolidates water-fauna heads in perception frames only. It excludes catching, spearing, hooking, "
            "netting, cooking, roasting, stewing, eating, meat, food, taboo, storm, rain, fear, biting, illness, story, "
            "myth, totem, target case forms, instruments, and unstable ngiwa polysemy."
        ),
        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 found 50 planned Kuku surfaces, 50 unique within-batch surfaces, and no exact accepted/revised cross-corpus duplicates.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_188.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guards passed: one retained water-fauna target per row, no loans, no target case forms, no instruments, no fishing/food/storm/fear/story field, common-noun A ERG in perception rows, and pronoun A bare.",
        command="python3 batch_scripts/bank_188.py static scan",
        artifact_path="batch_scripts/bank_188.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence,
             "under_review", confidence, "claude-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="bank",
        event_type="bank-success",
        actor="claude-main",
        detail="Banked 50 under_review Rule 146 water-fauna construction-consolidation rows.",
        command="python3 batch_scripts/bank_188.py",
        artifact_path="batch_scripts/bank_188.py",
        created_at=NOW,
    )
    db.commit()

    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    under_review = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    print(f"banked {LABEL}: rows=50, under_review={under_review}, verified_before_close={verified}")
    return 0


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