#!/usr/bin/env python3
"""Bank batch-224: Rule 182 construction consolidation after Rule 181."""

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

TARGET_HEADS = {
    "milkaji": "mullet",
    "dalkal": "sardine",
    "dandarrbina": "eelfish",
    "dawal": "trevally",
    "jarbir": "grunter",
    "jukar-jukarbina": "sand whiting",
    "julba": "minnow",
    "julmba": "sucker fish",
    "kudi": "barramundi",
    "kundur-kundur": "crescent perch",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "badibu", "baban", "balarri", "barrbal", "bayil", "bayilbayil", "bilaji", "bilmbin", "bububay", "bunjulu",
    "dalku", "dalmbal", "danbal", "dijarr", "dukul-barangkal", "jalil-jalil", "jalkay", "janbal",
    "jijirr", "jindi", "judi", "julaji", "kalngkan", "kalu", "kanyaji", "karrulji", "kijukum", "kilkirr",
    "kubarr", "kubija", "kubu-kubu", "kundurr-kundurr", "kurriyala", "kurruba", "kurrubal", "kuyu",
    "mangkurr-mangkurr", "mawul", "midir", "mujarrka", "murrabal", "murraja", "ngalkun", "ngarmu",
    "ngiwa", "walarrji", "walbul-walbul", "walkan", "wara", "wuyumbu", "yaba", "yaburr", "yalnganji",
    "yawu", "yidi", "yidilnyul", "yubuji",
    "badur", "makarr", "yinba", "yirrmba", "kanya", "banda", "kayil", "mungkil", "mandurr",
    "kuyalin", "karangaji", "karraway", "marrkabina", "ngarrakaja", "ngarruy", "munja-l", "murrngal",
}
DENY_ENGLISH = (
    "peewee", "freshwater", "red", "yellow", "eel", "kingfish", "species", "catch", "catches", "caught",
    "catching", "net", "hook", "line", "spear", "spears", "speared", "spearing", "bait", "eat", "eats",
    "ate", "eaten", "edible", "food", "meat", "cook", "cooked", "cooking", "taboo", "old people",
    "allowed to eat", "storm", "thunder", "rainstorm", "story", "story-site", "myth", "mythological",
    "place", "place-name", "river", "sea", "ocean", "water", "saltwater", "mangrove", "habitat",
    "reef", "scale", "fin", "tail", "body-part", "whiskers", "with whiskers", "source", "material",
    "use", "uses", "made", "poison", "danger", "bite", "bit", "biting", "kill", "killed", "hunting",
    "hunt", "plural", "many", "colour", "color", "productive reduplication", "reduplicate",
)


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


ROWS = [
    row(1, "The mullet is there.", "Milkaji yinyay.", "milkaji yinyay | mullet there", "r182_deictic_milkaji_there", ["milkaji", "yinyay"], "Rule 182 retains milkaji as mullet and rotates to yinyay deictic support; earache homonym remains closed."),
    row(2, "The sardine is there.", "Dalkal yinyay.", "dalkal yinyay | sardine there", "r182_deictic_dalkal_there", ["dalkal", "yinyay"], "Rule 182 retains dalkal as sardine and rotates to yinyay support; freshwater/red prose remains closed."),
    row(3, "The eelfish is there.", "Dandarrbina yinyay.", "dandarrbina yinyay | eelfish there", "r182_deictic_dandarrbina_there", ["dandarrbina", "yinyay"], "Rule 182 retains dandarrbina as eelfish; yellow freshwater eel prose remains closed."),
    row(4, "The trevally is there.", "Dawal yinyay.", "dawal yinyay | trevally there", "r182_deictic_dawal_there", ["dawal", "yinyay"], "Rule 182 retains dawal as trevally; kingfish alternate prose remains closed."),
    row(5, "The grunter is there.", "Jarbir yinyay.", "jarbir yinyay | grunter there", "r182_deictic_jarbir_there", ["jarbir", "yinyay"], "Rule 182 retains jarbir as grunter; generic species prose remains closed."),
    row(6, "The sand whiting is there.", "Jukar-jukarbina yinyay.", "jukar-jukarbina yinyay | sand.whiting there", "r182_deictic_jukar_jukarbina_there", ["jukar-jukarbina", "yinyay"], "Rule 182 retains jukar-jukarbina as sand whiting; no sand/place or productive reduplication row."),
    row(7, "The minnow is there.", "Julba yinyay.", "julba yinyay | minnow there", "r182_deictic_julba_there", ["julba", "yinyay"], "Rule 182 retains julba as minnow; freshwater prose remains closed."),
    row(8, "The sucker fish is there.", "Julmba yinyay.", "julmba yinyay | sucker.fish there", "r182_deictic_julmba_there", ["julmba", "yinyay"], "Rule 182 retains julmba as sucker fish; sucking/action derivation remains closed."),
    row(9, "The barramundi is there.", "Kudi yinyay.", "kudi yinyay | barramundi there", "r182_deictic_kudi_there", ["kudi", "yinyay"], "Rule 182 retains kudi as barramundi; murrabal equivalent drift remains closed."),
    row(10, "The crescent perch is there.", "Kundur-kundur yinyay.", "kundur-kundur yinyay | crescent.perch there", "r182_deictic_kundur_kundur_there", ["kundur-kundur", "yinyay"], "Rule 182 retains kundur-kundur as crescent perch; reduplication is lexical only."),
    row(11, "I see the mullet here.", "Ngayu milkaji yaluy nyajil.", "ngayu milkaji yaluy nyaji-l | I mullet here see-NONPAST", "r182_present_i_milkaji_here", ["ngayu", "milkaji", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; target object bare."),
    row(12, "I see the sardine here.", "Ngayu dalkal yaluy nyajil.", "ngayu dalkal yaluy nyaji-l | I sardine here see-NONPAST", "r182_present_i_dalkal_here", ["ngayu", "dalkal", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; selected sardine sense only."),
    row(13, "I see the eelfish here.", "Ngayu dandarrbina yaluy nyajil.", "ngayu dandarrbina yaluy nyaji-l | I eelfish here see-NONPAST", "r182_present_i_dandarrbina_here", ["ngayu", "dandarrbina", "yaluy", "nyaji-l"], "First-person present perception; colour and habitat prose remain closed."),
    row(14, "I see the trevally here.", "Ngayu dawal yaluy nyajil.", "ngayu dawal yaluy nyaji-l | I trevally here see-NONPAST", "r182_present_i_dawal_here", ["ngayu", "dawal", "yaluy", "nyaji-l"], "First-person present perception; kingfish alternate prose remains closed."),
    row(15, "I see the grunter here.", "Ngayu jarbir yaluy nyajil.", "ngayu jarbir yaluy nyaji-l | I grunter here see-NONPAST", "r182_present_i_jarbir_here", ["ngayu", "jarbir", "yaluy", "nyaji-l"], "First-person present perception; generic species prose not imported."),
    row(16, "I see the sand whiting here.", "Ngayu jukar-jukarbina yaluy nyajil.", "ngayu jukar-jukarbina yaluy nyaji-l | I sand.whiting here see-NONPAST", "r182_present_i_jukar_jukarbina_here", ["ngayu", "jukar-jukarbina", "yaluy", "nyaji-l"], "First-person present perception; sand/place derivation remains closed."),
    row(17, "I see the minnow here.", "Ngayu julba yaluy nyajil.", "ngayu julba yaluy nyaji-l | I minnow here see-NONPAST", "r182_present_i_julba_here", ["ngayu", "julba", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; target object bare."),
    row(18, "I see the sucker fish here.", "Ngayu julmba yaluy nyajil.", "ngayu julmba yaluy nyaji-l | I sucker.fish here see-NONPAST", "r182_present_i_julmba_here", ["ngayu", "julmba", "yaluy", "nyaji-l"], "First-person present perception; no sucking/action derivation."),
    row(19, "I see the barramundi here.", "Ngayu kudi yaluy nyajil.", "ngayu kudi yaluy nyaji-l | I barramundi here see-NONPAST", "r182_present_i_kudi_here", ["ngayu", "kudi", "yaluy", "nyaji-l"], "First-person present perception; murrabal equivalent not opened."),
    row(20, "I see the crescent perch here.", "Ngayu kundur-kundur yaluy nyajil.", "ngayu kundur-kundur yaluy nyaji-l | I crescent.perch here see-NONPAST", "r182_present_i_kundur_kundur_here", ["ngayu", "kundur-kundur", "yaluy", "nyaji-l"], "First-person present perception; lexical reduplication only."),
    row(21, "You see the mullet here.", "Yundu milkaji yaluy nyajil.", "yundu milkaji yaluy nyaji-l | you mullet here see-NONPAST", "r182_present_you_milkaji_here", ["yundu", "milkaji", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support; homonym closed."),
    row(22, "You see the sardine here.", "Yundu dalkal yaluy nyajil.", "yundu dalkal yaluy nyaji-l | you sardine here see-NONPAST", "r182_present_you_dalkal_here", ["yundu", "dalkal", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support; selected sense only."),
    row(23, "You see the eelfish here.", "Yundu dandarrbina yaluy nyajil.", "yundu dandarrbina yaluy nyaji-l | you eelfish here see-NONPAST", "r182_present_you_dandarrbina_here", ["yundu", "dandarrbina", "yaluy", "nyaji-l"], "Second-person present perception; colour and habitat prose remain closed."),
    row(24, "You see the trevally here.", "Yundu dawal yaluy nyajil.", "yundu dawal yaluy nyaji-l | you trevally here see-NONPAST", "r182_present_you_dawal_here", ["yundu", "dawal", "yaluy", "nyaji-l"], "Second-person present perception; kingfish alternate prose remains closed."),
    row(25, "You see the grunter here.", "Yundu jarbir yaluy nyajil.", "yundu jarbir yaluy nyaji-l | you grunter here see-NONPAST", "r182_present_you_jarbir_here", ["yundu", "jarbir", "yaluy", "nyaji-l"], "Second-person present perception; generic species prose not imported."),
    row(26, "You see the sand whiting here.", "Yundu jukar-jukarbina yaluy nyajil.", "yundu jukar-jukarbina yaluy nyaji-l | you sand.whiting here see-NONPAST", "r182_present_you_jukar_jukarbina_here", ["yundu", "jukar-jukarbina", "yaluy", "nyaji-l"], "Second-person present perception; no sand/place or productive reduplication row."),
    row(27, "You see the minnow here.", "Yundu julba yaluy nyajil.", "yundu julba yaluy nyaji-l | you minnow here see-NONPAST", "r182_present_you_julba_here", ["yundu", "julba", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support; target object bare."),
    row(28, "You see the sucker fish here.", "Yundu julmba yaluy nyajil.", "yundu julmba yaluy nyaji-l | you sucker.fish here see-NONPAST", "r182_present_you_julmba_here", ["yundu", "julmba", "yaluy", "nyaji-l"], "Second-person present perception; no action derivation."),
    row(29, "You see the barramundi here.", "Yundu kudi yaluy nyajil.", "yundu kudi yaluy nyaji-l | you barramundi here see-NONPAST", "r182_present_you_kudi_here", ["yundu", "kudi", "yaluy", "nyaji-l"], "Second-person present perception; selected kudi head only."),
    row(30, "You see the crescent perch here.", "Yundu kundur-kundur yaluy nyajil.", "yundu kundur-kundur yaluy nyaji-l | you crescent.perch here see-NONPAST", "r182_present_you_kundur_kundur_here", ["yundu", "kundur-kundur", "yaluy", "nyaji-l"], "Second-person present perception; target lexical form retained."),
    row(31, "They saw the mullet here.", "Jana milkaji yaluy nyajin.", "jana milkaji yaluy nyaji-ny | they mullet here see-PAST", "r182_past_they_milkaji_here", ["jana", "milkaji", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support; homonym closed."),
    row(32, "They saw the sardine here.", "Jana dalkal yaluy nyajin.", "jana dalkal yaluy nyaji-ny | they sardine here see-PAST", "r182_past_they_dalkal_here", ["jana", "dalkal", "yaluy", "nyaji-l"], "Third-person plural past perception; selected sardine sense only."),
    row(33, "They saw the eelfish here.", "Jana dandarrbina yaluy nyajin.", "jana dandarrbina yaluy nyaji-ny | they eelfish here see-PAST", "r182_past_they_dandarrbina_here", ["jana", "dandarrbina", "yaluy", "nyaji-l"], "Third-person plural past perception; colour and habitat prose remain closed."),
    row(34, "They saw the trevally here.", "Jana dawal yaluy nyajin.", "jana dawal yaluy nyaji-ny | they trevally here see-PAST", "r182_past_they_dawal_here", ["jana", "dawal", "yaluy", "nyaji-l"], "Third-person plural past perception; kingfish alternate prose remains closed."),
    row(35, "They saw the grunter here.", "Jana jarbir yaluy nyajin.", "jana jarbir yaluy nyaji-ny | they grunter here see-PAST", "r182_past_they_jarbir_here", ["jana", "jarbir", "yaluy", "nyaji-l"], "Third-person plural past perception; generic species prose remains closed."),
    row(36, "They saw the sand whiting here.", "Jana jukar-jukarbina yaluy nyajin.", "jana jukar-jukarbina yaluy nyaji-ny | they sand.whiting here see-PAST", "r182_past_they_jukar_jukarbina_here", ["jana", "jukar-jukarbina", "yaluy", "nyaji-l"], "Third-person plural past perception; sand/place derivation closed."),
    row(37, "They saw the minnow here.", "Jana julba yaluy nyajin.", "jana julba yaluy nyaji-ny | they minnow here see-PAST", "r182_past_they_julba_here", ["jana", "julba", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(38, "They saw the sucker fish here.", "Jana julmba yaluy nyajin.", "jana julmba yaluy nyaji-ny | they sucker.fish here see-PAST", "r182_past_they_julmba_here", ["jana", "julmba", "yaluy", "nyaji-l"], "Third-person plural past perception; no action derivation."),
    row(39, "They saw the barramundi here.", "Jana kudi yaluy nyajin.", "jana kudi yaluy nyaji-ny | they barramundi here see-PAST", "r182_past_they_kudi_here", ["jana", "kudi", "yaluy", "nyaji-l"], "Third-person plural past perception; murrabal equivalent not opened."),
    row(40, "They saw the crescent perch here.", "Jana kundur-kundur yaluy nyajin.", "jana kundur-kundur yaluy nyaji-ny | they crescent.perch here see-PAST", "r182_past_they_kundur_kundur_here", ["jana", "kundur-kundur", "yaluy", "nyaji-l"], "Third-person plural past perception; target lexical form retained."),
    row(41, "We see the mullet there.", "Ngana milkaji yinyay nyajil.", "ngana milkaji yinyay nyaji-l | we mullet there see-NONPAST", "r182_present_we_milkaji_there", ["ngana", "milkaji", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support; homonym closed."),
    row(42, "We see the sardine there.", "Ngana dalkal yinyay nyajil.", "ngana dalkal yinyay nyaji-l | we sardine there see-NONPAST", "r182_present_we_dalkal_there", ["ngana", "dalkal", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support; selected sense only."),
    row(43, "We see the eelfish there.", "Ngana dandarrbina yinyay nyajil.", "ngana dandarrbina yinyay nyaji-l | we eelfish there see-NONPAST", "r182_present_we_dandarrbina_there", ["ngana", "dandarrbina", "yinyay", "nyaji-l"], "Inclusive present perception; colour and habitat prose remain closed."),
    row(44, "We see the trevally there.", "Ngana dawal yinyay nyajil.", "ngana dawal yinyay nyaji-l | we trevally there see-NONPAST", "r182_present_we_dawal_there", ["ngana", "dawal", "yinyay", "nyaji-l"], "Inclusive present perception; selected trevally sense only."),
    row(45, "We see the grunter there.", "Ngana jarbir yinyay nyajil.", "ngana jarbir yinyay nyaji-l | we grunter there see-NONPAST", "r182_present_we_jarbir_there", ["ngana", "jarbir", "yinyay", "nyaji-l"], "Inclusive present perception; generic species prose remains closed."),
    row(46, "We see the sand whiting there.", "Ngana jukar-jukarbina yinyay nyajil.", "ngana jukar-jukarbina yinyay nyaji-l | we sand.whiting there see-NONPAST", "r182_present_we_jukar_jukarbina_there", ["ngana", "jukar-jukarbina", "yinyay", "nyaji-l"], "Inclusive present perception; no sand/place derivation."),
    row(47, "We see the minnow there.", "Ngana julba yinyay nyajil.", "ngana julba yinyay nyaji-l | we minnow there see-NONPAST", "r182_present_we_julba_there", ["ngana", "julba", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support; target object bare."),
    row(48, "We see the sucker fish there.", "Ngana julmba yinyay nyajil.", "ngana julmba yinyay nyaji-l | we sucker.fish there see-NONPAST", "r182_present_we_julmba_there", ["ngana", "julmba", "yinyay", "nyaji-l"], "Inclusive present perception; no action derivation."),
    row(49, "We see the barramundi there.", "Ngana kudi yinyay nyajil.", "ngana kudi yinyay nyaji-l | we barramundi there see-NONPAST", "r182_present_we_kudi_there", ["ngana", "kudi", "yinyay", "nyaji-l"], "Inclusive present perception; selected kudi head only."),
    row(50, "We see the crescent perch there.", "Ngana kundur-kundur yinyay nyajil.", "ngana kundur-kundur yinyay nyaji-l | we crescent.perch there see-NONPAST", "r182_present_we_kundur_kundur_there", ["ngana", "kundur-kundur", "yinyay", "nyaji-l"], "Inclusive present perception; lexical reduplication only."),
]


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|mba|mbu|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu|iji|nda|ndu|anda|undu|unji|nji|kari|baka)\b", low) is not None


def english_has_denied(english_low: str, denied: str) -> bool:
    return denied in english_low if " " in denied else re.search(rf"\b{re.escape(denied)}\b", english_low) is not None


def scan_static() -> list[str]:
    issues: list[str] = []
    if len(ROWS) != 50:
        issues.append(f"{LABEL}: expected 50 rows, found {len(ROWS)}")
    seen_ku: set[str] = set()
    for expected, row_data in enumerate(ROWS, start=1):
        seq, english, kuku, analysis, frame, _tier, words_used, loans_used, evidence, confidence = row_data
        label = f"{LABEL}.{seq:02d}"
        low = kuku.lower()
        english_low = english.lower()
        words = json.loads(words_used)
        if seq != expected:
            issues.append(f"{label}: sequence mismatch; 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("r182_"):
            issues.append(f"{label}: Rule 182 frame must start with r182_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        if json.loads(loans_used):
            issues.append(f"{label}: no loans are admitted in Rule 182")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied fish/use/old-field 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 retained Rule 181 target head, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected.replace(" ", ".") not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yinyay") or "yinyay" not in words or "there" not in english_low:
                issues.append(f"{label}: Rule 182 deictic rows require yinyay/there")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 182 perception rows must use nyaji-l")
            first = first_word(low)
            if first not in PRONOUN_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun")
            if 11 <= seq <= 20 and (first != "ngayu" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 11-20 require ngayu + yaluy/here")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yaluy/here")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yaluy") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yaluy + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yinyay/there")
            if "nyajin" in low and "see-PAST" not in analysis:
                issues.append(f"{label}: nyajin must be glossed as see-PAST")
            if "nyajil" in low and "see-NONPAST" not in analysis:
                issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied fish event/use/polysemy field in English")
        if not evidence or not confidence:
            issues.append(f"{label}: missing evidence/confidence")
    return issues


def main() -> int:
    issues = scan_static()
    if issues:
        print("pre-bank scan failed:")
        for issue in issues:
            print(f"  - {issue}")
        return 1

    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    existing = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()
    if existing:
        batch_id = existing[0]
        accepted = db.execute(
            "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status IN ('accepted','revised')",
            (batch_id,),
        ).fetchone()[0]
        if accepted:
            raise SystemExit(f"{LABEL} already has accepted/revised rows; refusing to overwrite")
        db.execute("DELETE FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)", (batch_id,))
        db.execute("DELETE FROM 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 182 draft: construction consolidation after Rule 181", "operator-guide-2026-07-08", "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 182 source pass retained exactly the ten Rule 181 fish-reference heads: milkaji, dalkal, dandarrbina, dawal, jarbir, jukar-jukarbina, julba, julmba, kudi, and kundur-kundur. Fresh dictionary readback reconfirmed selected senses and traps: milkaji earache homonym, dalkal freshwater/red prose, dandarrbina yellow freshwater eel prose, dawal kingfish alternate prose, jarbir generic species prose, jukar-jukarbina sand/place derivation, julba freshwater prose, julmba sucking/action derivation, kudi/murrabal equivalent drift, and kundur-kundur lexical reduplication only. Patz readback reconfirmed yaluy/yinyay, nyaji-l/nyaji-ny, absolutive bare objects, and bare pronoun A forms.",
                 command="rg/sed dictionary YAML readback; rg/sed Patz grammar readback; sqlite corpus 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 182 is a construction consolidation pass for the Rule 181 fish-reference field. It admits no new fish heads and excludes catching, netting, hook/line, spearing, bait, eating, cooking, food, taboo, storm/thunder, story, place, water/river/sea/habitat, fish body-part terms, target case, target compounds, possession, plural derivation, colour predicates, homograph senses, productive reduplication, and event claims.",
                 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/under_review cross-corpus duplicates.",
                 command="sqlite exact lower(trim(kuku)) duplicate scan before banking", artifact_path="batch_scripts/bank_224.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one retained Rule 181 fish target per row; all targets bare; no loans; no nonselected fish/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_224.py static scan", artifact_path="batch_scripts/bank_224.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, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()

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


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