#!/usr/bin/env python3
"""Bank batch-218: Rule 176 construction consolidation after Rule 175."""

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

TARGET_HEADS = {
    "banamu": "fresh water snake",
    "binju": "light bellied black snake",
    "dukul-mukul": "dukul-mukul lizard",
    "jirabay": "ground lizard",
    "junbirr": "small lizard",
    "kabuljaka": "striped water snake",
    "kulmba-kulmba": "gecko",
    "kurriyala": "carpet snake",
    "ngawurr-ngawun": "freshwater crocodile",
    "ngumbul": "sea snake",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "jarba", "wali-yindu-wali-yindu", "jalbil", "kalkarrumbarr", "kurmba-kurmba", "jimalili",
    "yuday", "barka", "bajabaja", "jadi", "jinkalmu", "bajalji", "kalajarr", "bilngkumu",
    "ngawiya", "walkarr", "bakay", "bubal", "jabil", "kungkun", "kundurr", "bindimu",
    "kalkamuku", "yirku-yirku",
}
DENY_ENGLISH = (
    "wrong marriage", "marriage", "cooking", "cooked", "cook", "poison", "poisonous", "fish", "grunter",
    "belt", "run", "runs", "running", "story", "story-site", "legend", "myth", "mythological", "food",
    "edible", "eat", "eats", "ate", "eaten", "hunt", "hunting", "catch", "catches", "caught", "chase",
    "chases", "chased", "firestick", "eye", "eyes", "fighter", "fierce", "place", "place-name", "river",
    "egg", "eggs", "body-part", "head", "belly", "marking", "markings", "use", "uses", "made",
)


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 fresh water snake is there.", "Banamu yinyay.", "banamu yinyay | fresh.water.snake there", "r176_deictic_banamu_there", ["banamu", "yinyay"], "Rule 176 consolidates banamu as fresh water snake with yinyay support."),
    row(2, "The light bellied black snake is there.", "Binju yinyay.", "binju yinyay | light.bellied.black.snake there", "r176_deictic_binju_there", ["binju", "yinyay"], "Rule 176 consolidates binju as light bellied black snake; wrong-marriage/cooking/poison senses remain closed."),
    row(3, "The dukul-mukul lizard is there.", "Dukul-mukul yinyay.", "dukul-mukul yinyay | dukul-mukul.lizard there", "r176_deictic_dukulmukul_there", ["dukul-mukul", "yinyay"], "Rule 176 consolidates dukul-mukul as a whole lizard head."),
    row(4, "The ground lizard is there.", "Jirabay yinyay.", "jirabay yinyay | ground.lizard there", "r176_deictic_jirabay_there", ["jirabay", "yinyay"], "Rule 176 consolidates jirabay as ground lizard; comparison/place prose not imported."),
    row(5, "The small lizard is there.", "Junbirr yinyay.", "junbirr yinyay | small.lizard there", "r176_deictic_junbirr_there", ["junbirr", "yinyay"], "Rule 176 consolidates junbirr as small lizard; marking/body-part prose not imported."),
    row(6, "The striped water snake is there.", "Kabuljaka yinyay.", "kabuljaka yinyay | striped.water.snake there", "r176_deictic_kabuljaka_there", ["kabuljaka", "yinyay"], "Rule 176 consolidates kabuljaka as striped water snake."),
    row(7, "The gecko is there.", "Kulmba-kulmba yinyay.", "kulmba-kulmba yinyay | gecko there", "r176_deictic_kulmbakulmba_there", ["kulmba-kulmba", "yinyay"], "Rule 176 consolidates kulmba-kulmba as gecko; whole lexical head."),
    row(8, "The carpet snake is there.", "Kurriyala yinyay.", "kurriyala yinyay | carpet.snake there", "r176_deictic_kurriyala_there", ["kurriyala", "yinyay"], "Rule 176 consolidates kurriyala as carpet snake; fish/story/source/run-away prose remains closed."),
    row(9, "The freshwater crocodile is there.", "Ngawurr-ngawun yinyay.", "ngawurr-ngawun yinyay | freshwater.crocodile there", "r176_deictic_ngawurrngawun_there", ["ngawurr-ngawun", "yinyay"], "Rule 176 consolidates ngawurr-ngawun as freshwater crocodile."),
    row(10, "The sea snake is there.", "Ngumbul yinyay.", "ngumbul yinyay | sea.snake there", "r176_deictic_ngumbul_there", ["ngumbul", "yinyay"], "Rule 176 consolidates ngumbul as sea snake."),
    row(11, "I see the fresh water snake here.", "Ngayu banamu yaluy nyajil.", "ngayu banamu yaluy nyaji-l | I fresh.water.snake here see-NONPAST", "r176_present_i_banamu_here", ["ngayu", "banamu", "yaluy", "nyaji-l"], "First-person present perception with bare target and yaluy support."),
    row(12, "I see the light bellied black snake here.", "Ngayu binju yaluy nyajil.", "ngayu binju yaluy nyaji-l | I light.bellied.black.snake here see-NONPAST", "r176_present_i_binju_here", ["ngayu", "binju", "yaluy", "nyaji-l"], "First-person present perception; selected reptile sense only."),
    row(13, "I see the dukul-mukul lizard here.", "Ngayu dukul-mukul yaluy nyajil.", "ngayu dukul-mukul yaluy nyaji-l | I dukul-mukul.lizard here see-NONPAST", "r176_present_i_dukulmukul_here", ["ngayu", "dukul-mukul", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(14, "I see the ground lizard here.", "Ngayu jirabay yaluy nyajil.", "ngayu jirabay yaluy nyaji-l | I ground.lizard here see-NONPAST", "r176_present_i_jirabay_here", ["ngayu", "jirabay", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(15, "I see the small lizard here.", "Ngayu junbirr yaluy nyajil.", "ngayu junbirr yaluy nyaji-l | I small.lizard here see-NONPAST", "r176_present_i_junbirr_here", ["ngayu", "junbirr", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(16, "I see the striped water snake here.", "Ngayu kabuljaka yaluy nyajil.", "ngayu kabuljaka yaluy nyaji-l | I striped.water.snake here see-NONPAST", "r176_present_i_kabuljaka_here", ["ngayu", "kabuljaka", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(17, "I see the gecko here.", "Ngayu kulmba-kulmba yaluy nyajil.", "ngayu kulmba-kulmba yaluy nyaji-l | I gecko here see-NONPAST", "r176_present_i_kulmbakulmba_here", ["ngayu", "kulmba-kulmba", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(18, "I see the carpet snake here.", "Ngayu kurriyala yaluy nyajil.", "ngayu kurriyala yaluy nyaji-l | I carpet.snake here see-NONPAST", "r176_present_i_kurriyala_here", ["ngayu", "kurriyala", "yaluy", "nyaji-l"], "First-person present perception; selected reptile sense only."),
    row(19, "I see the freshwater crocodile here.", "Ngayu ngawurr-ngawun yaluy nyajil.", "ngayu ngawurr-ngawun yaluy nyaji-l | I freshwater.crocodile here see-NONPAST", "r176_present_i_ngawurrngawun_here", ["ngayu", "ngawurr-ngawun", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(20, "I see the sea snake here.", "Ngayu ngumbul yaluy nyajil.", "ngayu ngumbul yaluy nyaji-l | I sea.snake here see-NONPAST", "r176_present_i_ngumbul_here", ["ngayu", "ngumbul", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(21, "You see the fresh water snake here.", "Yundu banamu yaluy nyajil.", "yundu banamu yaluy nyaji-l | you fresh.water.snake here see-NONPAST", "r176_present_you_banamu_here", ["yundu", "banamu", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(22, "You see the light bellied black snake here.", "Yundu binju yaluy nyajil.", "yundu binju yaluy nyaji-l | you light.bellied.black.snake here see-NONPAST", "r176_present_you_binju_here", ["yundu", "binju", "yaluy", "nyaji-l"], "Second-person present perception; selected reptile sense only."),
    row(23, "You see the dukul-mukul lizard here.", "Yundu dukul-mukul yaluy nyajil.", "yundu dukul-mukul yaluy nyaji-l | you dukul-mukul.lizard here see-NONPAST", "r176_present_you_dukulmukul_here", ["yundu", "dukul-mukul", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(24, "You see the ground lizard here.", "Yundu jirabay yaluy nyajil.", "yundu jirabay yaluy nyaji-l | you ground.lizard here see-NONPAST", "r176_present_you_jirabay_here", ["yundu", "jirabay", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(25, "You see the small lizard here.", "Yundu junbirr yaluy nyajil.", "yundu junbirr yaluy nyaji-l | you small.lizard here see-NONPAST", "r176_present_you_junbirr_here", ["yundu", "junbirr", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(26, "You see the striped water snake here.", "Yundu kabuljaka yaluy nyajil.", "yundu kabuljaka yaluy nyaji-l | you striped.water.snake here see-NONPAST", "r176_present_you_kabuljaka_here", ["yundu", "kabuljaka", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(27, "You see the gecko here.", "Yundu kulmba-kulmba yaluy nyajil.", "yundu kulmba-kulmba yaluy nyaji-l | you gecko here see-NONPAST", "r176_present_you_kulmbakulmba_here", ["yundu", "kulmba-kulmba", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(28, "You see the carpet snake here.", "Yundu kurriyala yaluy nyajil.", "yundu kurriyala yaluy nyaji-l | you carpet.snake here see-NONPAST", "r176_present_you_kurriyala_here", ["yundu", "kurriyala", "yaluy", "nyaji-l"], "Second-person present perception; selected reptile sense only."),
    row(29, "You see the freshwater crocodile here.", "Yundu ngawurr-ngawun yaluy nyajil.", "yundu ngawurr-ngawun yaluy nyaji-l | you freshwater.crocodile here see-NONPAST", "r176_present_you_ngawurrngawun_here", ["yundu", "ngawurr-ngawun", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(30, "You see the sea snake here.", "Yundu ngumbul yaluy nyajil.", "yundu ngumbul yaluy nyaji-l | you sea.snake here see-NONPAST", "r176_present_you_ngumbul_here", ["yundu", "ngumbul", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(31, "They saw the fresh water snake here.", "Jana banamu yaluy nyajin.", "jana banamu yaluy nyaji-ny | they fresh.water.snake here see-PAST", "r176_past_they_banamu_here", ["jana", "banamu", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(32, "They saw the light bellied black snake here.", "Jana binju yaluy nyajin.", "jana binju yaluy nyaji-ny | they light.bellied.black.snake here see-PAST", "r176_past_they_binju_here", ["jana", "binju", "yaluy", "nyaji-l"], "Third-person plural past perception; selected reptile sense only."),
    row(33, "They saw the dukul-mukul lizard here.", "Jana dukul-mukul yaluy nyajin.", "jana dukul-mukul yaluy nyaji-ny | they dukul-mukul.lizard here see-PAST", "r176_past_they_dukulmukul_here", ["jana", "dukul-mukul", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(34, "They saw the ground lizard here.", "Jana jirabay yaluy nyajin.", "jana jirabay yaluy nyaji-ny | they ground.lizard here see-PAST", "r176_past_they_jirabay_here", ["jana", "jirabay", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(35, "They saw the small lizard here.", "Jana junbirr yaluy nyajin.", "jana junbirr yaluy nyaji-ny | they small.lizard here see-PAST", "r176_past_they_junbirr_here", ["jana", "junbirr", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(36, "They saw the striped water snake here.", "Jana kabuljaka yaluy nyajin.", "jana kabuljaka yaluy nyaji-ny | they striped.water.snake here see-PAST", "r176_past_they_kabuljaka_here", ["jana", "kabuljaka", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(37, "They saw the gecko here.", "Jana kulmba-kulmba yaluy nyajin.", "jana kulmba-kulmba yaluy nyaji-ny | they gecko here see-PAST", "r176_past_they_kulmbakulmba_here", ["jana", "kulmba-kulmba", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(38, "They saw the carpet snake here.", "Jana kurriyala yaluy nyajin.", "jana kurriyala yaluy nyaji-ny | they carpet.snake here see-PAST", "r176_past_they_kurriyala_here", ["jana", "kurriyala", "yaluy", "nyaji-l"], "Third-person plural past perception; selected reptile sense only."),
    row(39, "They saw the freshwater crocodile here.", "Jana ngawurr-ngawun yaluy nyajin.", "jana ngawurr-ngawun yaluy nyaji-ny | they freshwater.crocodile here see-PAST", "r176_past_they_ngawurrngawun_here", ["jana", "ngawurr-ngawun", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(40, "They saw the sea snake here.", "Jana ngumbul yaluy nyajin.", "jana ngumbul yaluy nyaji-ny | they sea.snake here see-PAST", "r176_past_they_ngumbul_here", ["jana", "ngumbul", "yaluy", "nyaji-l"], "Third-person plural past perception; target bare."),
    row(41, "We see the fresh water snake there.", "Ngana banamu yinyay nyajil.", "ngana banamu yinyay nyaji-l | we fresh.water.snake there see-NONPAST", "r176_present_we_banamu_there", ["ngana", "banamu", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(42, "We see the light bellied black snake there.", "Ngana binju yinyay nyajil.", "ngana binju yinyay nyaji-l | we light.bellied.black.snake there see-NONPAST", "r176_present_we_binju_there", ["ngana", "binju", "yinyay", "nyaji-l"], "Inclusive present perception; selected reptile sense only."),
    row(43, "We see the dukul-mukul lizard there.", "Ngana dukul-mukul yinyay nyajil.", "ngana dukul-mukul yinyay nyaji-l | we dukul-mukul.lizard there see-NONPAST", "r176_present_we_dukulmukul_there", ["ngana", "dukul-mukul", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(44, "We see the ground lizard there.", "Ngana jirabay yinyay nyajil.", "ngana jirabay yinyay nyaji-l | we ground.lizard there see-NONPAST", "r176_present_we_jirabay_there", ["ngana", "jirabay", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(45, "We see the small lizard there.", "Ngana junbirr yinyay nyajil.", "ngana junbirr yinyay nyaji-l | we small.lizard there see-NONPAST", "r176_present_we_junbirr_there", ["ngana", "junbirr", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(46, "We see the striped water snake there.", "Ngana kabuljaka yinyay nyajil.", "ngana kabuljaka yinyay nyaji-l | we striped.water.snake there see-NONPAST", "r176_present_we_kabuljaka_there", ["ngana", "kabuljaka", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(47, "We see the gecko there.", "Ngana kulmba-kulmba yinyay nyajil.", "ngana kulmba-kulmba yinyay nyaji-l | we gecko there see-NONPAST", "r176_present_we_kulmbakulmba_there", ["ngana", "kulmba-kulmba", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(48, "We see the carpet snake there.", "Ngana kurriyala yinyay nyajil.", "ngana kurriyala yinyay nyaji-l | we carpet.snake there see-NONPAST", "r176_present_we_kurriyala_there", ["ngana", "kurriyala", "yinyay", "nyaji-l"], "Inclusive present perception; selected reptile sense only."),
    row(49, "We see the freshwater crocodile there.", "Ngana ngawurr-ngawun yinyay nyajil.", "ngana ngawurr-ngawun yinyay nyaji-l | we freshwater.crocodile there see-NONPAST", "r176_present_we_ngawurrngawun_there", ["ngana", "ngawurr-ngawun", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
    row(50, "We see the sea snake there.", "Ngana ngumbul yinyay nyajil.", "ngana ngumbul yinyay nyaji-l | we sea.snake there see-NONPAST", "r176_present_we_ngumbul_there", ["ngana", "ngumbul", "yinyay", "nyaji-l"], "Inclusive present perception; target bare."),
]


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("r176_"):
            issues.append(f"{label}: Rule 176 frame must start with r176_")
        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 176")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied rejected/use 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 175 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 176 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 176 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 reptile 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 176 draft: construction consolidation after Rule 175", "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 176 source pass retained exactly the ten Rule 175 reptile-reference heads: banamu, binju, dukul-mukul, jirabay, junbirr, kabuljaka, kulmba-kulmba, kurriyala, ngawurr-ngawun, and ngumbul. Dictionary exact readback reconfirmed selected senses. Patz readback reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Corpus readback found the heads already present through Batch 217 accepted rows and zero Batch 218 rows before banking.",
                 command="rg dictionary readback; rg 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 176 is a construction consolidation pass for the Rule 175 reptile-reference field. It admits no new reptile heads and excludes wrong-marriage, cooking, poisonous, fish/grunter, belt/source, running-from, story, story-site, legend, mythological-person, food, edible, eating, hunting, catching, chase, firestick, eye/fighter, place, river, egg, body-part, target case, target compounds, possession, 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_218.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 175 reptile target per row; all targets bare; no loans; no rejected-reptile/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_218.py static scan", artifact_path="batch_scripts/bank_218.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())
