#!/usr/bin/env python3
"""Bank batch-223: Rule 181 fish reference lexical expansion after Rule 180."""

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-223"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-223-fish-reference-lexical-expansion-after-rule180-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", "dandarrbina-nyungu", "dawal-dawal", "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 here.", "Milkaji yaluy.", "milkaji yaluy | mullet here", "r181_deictic_milkaji_here", ["milkaji", "yaluy"], "Rule 181 admits milkaji as mullet; earache homonym and small/blue-tailed prose not opened."),
    row(2, "The sardine is here.", "Dalkal yaluy.", "dalkal yaluy | sardine here", "r181_deictic_dalkal_here", ["dalkal", "yaluy"], "Rule 181 admits dalkal as sardine; freshwater/red prose not opened."),
    row(3, "The eelfish is here.", "Dandarrbina yaluy.", "dandarrbina yaluy | eelfish here", "r181_deictic_dandarrbina_here", ["dandarrbina", "yaluy"], "Rule 181 admits dandarrbina as eelfish; yellow freshwater eel prose not opened."),
    row(4, "The trevally is here.", "Dawal yaluy.", "dawal yaluy | trevally here", "r181_deictic_dawal_here", ["dawal", "yaluy"], "Rule 181 admits dawal as trevally; kingfish alternate prose not opened."),
    row(5, "The grunter is here.", "Jarbir yaluy.", "jarbir yaluy | grunter here", "r181_deictic_jarbir_here", ["jarbir", "yaluy"], "Rule 181 admits jarbir as grunter; generic species prose not opened."),
    row(6, "The sand whiting is here.", "Jukar-jukarbina yaluy.", "jukar-jukarbina yaluy | sand.whiting here", "r181_deictic_jukar_jukarbina_here", ["jukar-jukarbina", "yaluy"], "Rule 181 admits jukar-jukarbina as sand whiting; no sand/place or reduplication row."),
    row(7, "The minnow is here.", "Julba yaluy.", "julba yaluy | minnow here", "r181_deictic_julba_here", ["julba", "yaluy"], "Rule 181 admits julba as minnow; freshwater prose not opened."),
    row(8, "The sucker fish is here.", "Julmba yaluy.", "julmba yaluy | sucker.fish here", "r181_deictic_julmba_here", ["julmba", "yaluy"], "Rule 181 admits julmba as sucker fish; no sucking/action row."),
    row(9, "The barramundi is here.", "Kudi yaluy.", "kudi yaluy | barramundi here", "r181_deictic_kudi_here", ["kudi", "yaluy"], "Rule 181 admits kudi as barramundi; murrabal equivalent not opened."),
    row(10, "The crescent perch is here.", "Kundur-kundur yaluy.", "kundur-kundur yaluy | crescent.perch here", "r181_deictic_kundur_kundur_here", ["kundur-kundur", "yaluy"], "Rule 181 admits kundur-kundur as crescent perch; no productive reduplication claim."),
    row(11, "I see the mullet.", "Ngayu milkaji nyajil.", "ngayu milkaji nyaji-l | I mullet see-NONPAST", "r181_present_i_milkaji", ["ngayu", "milkaji", "nyaji-l"], "First-person present perception; earache homonym not imported."),
    row(12, "I see the sardine.", "Ngayu dalkal nyajil.", "ngayu dalkal nyaji-l | I sardine see-NONPAST", "r181_present_i_dalkal", ["ngayu", "dalkal", "nyaji-l"], "First-person present perception; selected sardine sense only."),
    row(13, "I see the eelfish.", "Ngayu dandarrbina nyajil.", "ngayu dandarrbina nyaji-l | I eelfish see-NONPAST", "r181_present_i_dandarrbina", ["ngayu", "dandarrbina", "nyaji-l"], "First-person present perception; yellow freshwater eel prose not imported."),
    row(14, "I see the trevally.", "Ngayu dawal nyajil.", "ngayu dawal nyaji-l | I trevally see-NONPAST", "r181_present_i_dawal", ["ngayu", "dawal", "nyaji-l"], "First-person present perception; selected trevally sense only."),
    row(15, "I see the grunter.", "Ngayu jarbir nyajil.", "ngayu jarbir nyaji-l | I grunter see-NONPAST", "r181_present_i_jarbir", ["ngayu", "jarbir", "nyaji-l"], "First-person present perception; generic species prose not imported."),
    row(16, "I see the sand whiting.", "Ngayu jukar-jukarbina nyajil.", "ngayu jukar-jukarbina nyaji-l | I sand.whiting see-NONPAST", "r181_present_i_jukar_jukarbina", ["ngayu", "jukar-jukarbina", "nyaji-l"], "First-person present perception; sand/place derivation not opened."),
    row(17, "I see the minnow.", "Ngayu julba nyajil.", "ngayu julba nyaji-l | I minnow see-NONPAST", "r181_present_i_julba", ["ngayu", "julba", "nyaji-l"], "First-person present perception; selected minnow sense only."),
    row(18, "I see the sucker fish.", "Ngayu julmba nyajil.", "ngayu julmba nyaji-l | I sucker.fish see-NONPAST", "r181_present_i_julmba", ["ngayu", "julmba", "nyaji-l"], "First-person present perception; no action derivation."),
    row(19, "I see the barramundi.", "Ngayu kudi nyajil.", "ngayu kudi nyaji-l | I barramundi see-NONPAST", "r181_present_i_kudi", ["ngayu", "kudi", "nyaji-l"], "First-person present perception; murrabal equivalent not opened."),
    row(20, "I see the crescent perch.", "Ngayu kundur-kundur nyajil.", "ngayu kundur-kundur nyaji-l | I crescent.perch see-NONPAST", "r181_present_i_kundur_kundur", ["ngayu", "kundur-kundur", "nyaji-l"], "First-person present perception; target lexical form retained."),
    row(21, "You see the mullet there.", "Yundu milkaji yinyay nyajil.", "yundu milkaji yinyay nyaji-l | you mullet there see-NONPAST", "r181_present_you_milkaji_there", ["yundu", "milkaji", "yinyay", "nyaji-l"], "Second-person present perception with yinyay support; homonym closed."),
    row(22, "You see the sardine there.", "Yundu dalkal yinyay nyajil.", "yundu dalkal yinyay nyaji-l | you sardine there see-NONPAST", "r181_present_you_dalkal_there", ["yundu", "dalkal", "yinyay", "nyaji-l"], "Second-person present perception with yinyay support."),
    row(23, "You see the eelfish there.", "Yundu dandarrbina yinyay nyajil.", "yundu dandarrbina yinyay nyaji-l | you eelfish there see-NONPAST", "r181_present_you_dandarrbina_there", ["yundu", "dandarrbina", "yinyay", "nyaji-l"], "Second-person present perception; colour/habitat prose closed."),
    row(24, "You see the trevally there.", "Yundu dawal yinyay nyajil.", "yundu dawal yinyay nyaji-l | you trevally there see-NONPAST", "r181_present_you_dawal_there", ["yundu", "dawal", "yinyay", "nyaji-l"], "Second-person present perception; kingfish alternate prose closed."),
    row(25, "You see the grunter there.", "Yundu jarbir yinyay nyajil.", "yundu jarbir yinyay nyaji-l | you grunter there see-NONPAST", "r181_present_you_jarbir_there", ["yundu", "jarbir", "yinyay", "nyaji-l"], "Second-person present perception; generic species prose closed."),
    row(26, "You see the sand whiting there.", "Yundu jukar-jukarbina yinyay nyajil.", "yundu jukar-jukarbina yinyay nyaji-l | you sand.whiting there see-NONPAST", "r181_present_you_jukar_jukarbina_there", ["yundu", "jukar-jukarbina", "yinyay", "nyaji-l"], "Second-person present perception; no productive reduplication claim."),
    row(27, "You see the minnow there.", "Yundu julba yinyay nyajil.", "yundu julba yinyay nyaji-l | you minnow there see-NONPAST", "r181_present_you_julba_there", ["yundu", "julba", "yinyay", "nyaji-l"], "Second-person present perception with yinyay support."),
    row(28, "You see the sucker fish there.", "Yundu julmba yinyay nyajil.", "yundu julmba yinyay nyaji-l | you sucker.fish there see-NONPAST", "r181_present_you_julmba_there", ["yundu", "julmba", "yinyay", "nyaji-l"], "Second-person present perception; no action derivation."),
    row(29, "You see the barramundi there.", "Yundu kudi yinyay nyajil.", "yundu kudi yinyay nyaji-l | you barramundi there see-NONPAST", "r181_present_you_kudi_there", ["yundu", "kudi", "yinyay", "nyaji-l"], "Second-person present perception; kudi selected over murrabal."),
    row(30, "You see the crescent perch there.", "Yundu kundur-kundur yinyay nyajil.", "yundu kundur-kundur yinyay nyaji-l | you crescent.perch there see-NONPAST", "r181_present_you_kundur_kundur_there", ["yundu", "kundur-kundur", "yinyay", "nyaji-l"], "Second-person present perception; target lexical form retained."),
    row(31, "They saw the mullet there.", "Jana milkaji yinyay nyajin.", "jana milkaji yinyay nyaji-ny | they mullet there see-PAST", "r181_past_they_milkaji_there", ["jana", "milkaji", "yinyay", "nyaji-l"], "Third-person plural past perception with yinyay support; homonym closed."),
    row(32, "They saw the sardine there.", "Jana dalkal yinyay nyajin.", "jana dalkal yinyay nyaji-ny | they sardine there see-PAST", "r181_past_they_dalkal_there", ["jana", "dalkal", "yinyay", "nyaji-l"], "Third-person plural past perception; selected sardine sense only."),
    row(33, "They saw the eelfish there.", "Jana dandarrbina yinyay nyajin.", "jana dandarrbina yinyay nyaji-ny | they eelfish there see-PAST", "r181_past_they_dandarrbina_there", ["jana", "dandarrbina", "yinyay", "nyaji-l"], "Third-person plural past perception; colour/habitat prose closed."),
    row(34, "They saw the trevally there.", "Jana dawal yinyay nyajin.", "jana dawal yinyay nyaji-ny | they trevally there see-PAST", "r181_past_they_dawal_there", ["jana", "dawal", "yinyay", "nyaji-l"], "Third-person plural past perception; kingfish alternate prose closed."),
    row(35, "They saw the grunter there.", "Jana jarbir yinyay nyajin.", "jana jarbir yinyay nyaji-ny | they grunter there see-PAST", "r181_past_they_jarbir_there", ["jana", "jarbir", "yinyay", "nyaji-l"], "Third-person plural past perception; generic species prose closed."),
    row(36, "They saw the sand whiting there.", "Jana jukar-jukarbina yinyay nyajin.", "jana jukar-jukarbina yinyay nyaji-ny | they sand.whiting there see-PAST", "r181_past_they_jukar_jukarbina_there", ["jana", "jukar-jukarbina", "yinyay", "nyaji-l"], "Third-person plural past perception; no sand/place derivation."),
    row(37, "They saw the minnow there.", "Jana julba yinyay nyajin.", "jana julba yinyay nyaji-ny | they minnow there see-PAST", "r181_past_they_julba_there", ["jana", "julba", "yinyay", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(38, "They saw the sucker fish there.", "Jana julmba yinyay nyajin.", "jana julmba yinyay nyaji-ny | they sucker.fish there see-PAST", "r181_past_they_julmba_there", ["jana", "julmba", "yinyay", "nyaji-l"], "Third-person plural past perception; no action derivation."),
    row(39, "They saw the barramundi there.", "Jana kudi yinyay nyajin.", "jana kudi yinyay nyaji-ny | they barramundi there see-PAST", "r181_past_they_kudi_there", ["jana", "kudi", "yinyay", "nyaji-l"], "Third-person plural past perception; murrabal equivalent not opened."),
    row(40, "They saw the crescent perch there.", "Jana kundur-kundur yinyay nyajin.", "jana kundur-kundur yinyay nyaji-ny | they crescent.perch there see-PAST", "r181_past_they_kundur_kundur_there", ["jana", "kundur-kundur", "yinyay", "nyaji-l"], "Third-person plural past perception; target lexical form retained."),
    row(41, "We see the mullet here.", "Ngana milkaji yaluy nyajil.", "ngana milkaji yaluy nyaji-l | we mullet here see-NONPAST", "r181_present_we_milkaji_here", ["ngana", "milkaji", "yaluy", "nyaji-l"], "Inclusive present perception with yaluy support; homonym closed."),
    row(42, "We see the sardine here.", "Ngana dalkal yaluy nyajil.", "ngana dalkal yaluy nyaji-l | we sardine here see-NONPAST", "r181_present_we_dalkal_here", ["ngana", "dalkal", "yaluy", "nyaji-l"], "Inclusive present perception with yaluy support."),
    row(43, "We see the eelfish here.", "Ngana dandarrbina yaluy nyajil.", "ngana dandarrbina yaluy nyaji-l | we eelfish here see-NONPAST", "r181_present_we_dandarrbina_here", ["ngana", "dandarrbina", "yaluy", "nyaji-l"], "Inclusive present perception; colour/habitat prose closed."),
    row(44, "We see the trevally here.", "Ngana dawal yaluy nyajil.", "ngana dawal yaluy nyaji-l | we trevally here see-NONPAST", "r181_present_we_dawal_here", ["ngana", "dawal", "yaluy", "nyaji-l"], "Inclusive present perception; selected trevally sense only."),
    row(45, "We see the grunter here.", "Ngana jarbir yaluy nyajil.", "ngana jarbir yaluy nyaji-l | we grunter here see-NONPAST", "r181_present_we_jarbir_here", ["ngana", "jarbir", "yaluy", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(46, "We see the sand whiting here.", "Ngana jukar-jukarbina yaluy nyajil.", "ngana jukar-jukarbina yaluy nyaji-l | we sand.whiting here see-NONPAST", "r181_present_we_jukar_jukarbina_here", ["ngana", "jukar-jukarbina", "yaluy", "nyaji-l"], "Inclusive present perception; no sand/place derivation."),
    row(47, "We see the minnow here.", "Ngana julba yaluy nyajil.", "ngana julba yaluy nyaji-l | we minnow here see-NONPAST", "r181_present_we_julba_here", ["ngana", "julba", "yaluy", "nyaji-l"], "Inclusive present perception with yaluy support."),
    row(48, "We see the sucker fish here.", "Ngana julmba yaluy nyajil.", "ngana julmba yaluy nyaji-l | we sucker.fish here see-NONPAST", "r181_present_we_julmba_here", ["ngana", "julmba", "yaluy", "nyaji-l"], "Inclusive present perception; no action derivation."),
    row(49, "We see the barramundi here.", "Ngana kudi yaluy nyajil.", "ngana kudi yaluy nyaji-l | we barramundi here see-NONPAST", "r181_present_we_kudi_here", ["ngana", "kudi", "yaluy", "nyaji-l"], "Inclusive present perception; selected kudi head only."),
    row(50, "We see the crescent perch here.", "Ngana kundur-kundur yaluy nyajil.", "ngana kundur-kundur yaluy nyaji-l | we crescent.perch here see-NONPAST", "r181_present_we_kundur_kundur_here", ["ngana", "kundur-kundur", "yaluy", "nyaji-l"], "Inclusive present perception; no productive reduplication claim."),
]


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("r181_"):
            issues.append(f"{label}: Rule 181 frame must start with r181_")
        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 181")
        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 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, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 181 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 181 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":
                issues.append(f"{label}: rows 11-20 require ngayu")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            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 181 draft: fish reference lexical expansion after Rule 180", "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 181 source pass selected ten zero-hit fish-reference heads with exact dictionary readback: milkaji mullet, dalkal sardine, dandarrbina eelfish, dawal trevally, jarbir grunter, jukar-jukarbina sand whiting, julba minnow, julmba sucker fish, kudi barramundi, and kundur-kundur crescent perch. Dictionary readback retained selected senses and closed milkaji earache homonym, small/blue-tailed prose, freshwater/red, yellow freshwater eel, kingfish, generic species-of-fish prose, sand/place derivation, sucking/action semantics, murrabal equivalent drift, and productive reduplication claims. Patz readback reconfirmed yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Boundary-aware corpus readback found zero accepted/revised/under_review rows for selected targets.",
                 command="structured dictionary YAML readback; rg grammar readback; sqlite boundary-aware corpus readback",
                 artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="scope", event_type="lexical-scope", actor="claude-main",
                 detail="Rule 181 is a lexical fish reference pass for ten bare target heads. It excludes nonselected fish heads, 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, reduplication productivity, colour predicates, 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_223.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 selected 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_223.py static scan", artifact_path="batch_scripts/bank_223.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())
