#!/usr/bin/env python3
"""Bank batch-216: Rule 174 construction consolidation after Rule 173."""

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

TARGET_HEADS = {
    "barbarr": "young cassowary",
    "bayil-bayil": "mudlark",
    "biluwarra": "spoon bill bird",
    "binjul-binjul": "scarlet robin",
    "dijarr-dijin": "willie wagtail",
    "kurburrubun": "magpie",
    "kurkumbay": "butcherbird",
    "kurungka": "bronze wing pigeon",
    "munwingkul": "dove",
    "yindili": "forest kingfisher",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "babarr", "bujarr-bujarr", "dukunjuju", "kujuway", "yiki", "birmba", "dabway", "dakwul-dakwul",
    "dakwurr-dakwun", "dirrmbay", "kurrujuwa", "mirrku", "mulumu", "ngurrku", "walu-dalbaji",
    "wandi", "yalngkurr", "buyi", "nangki", "diburr", "dawa-dawa", "jamarbina", "nili-nili",
    "mabal", "kulbal", "kurranji", "dikal", "juku-juku", "kuludu", "juril-juril",
}
DENY_ENGLISH = (
    "fly", "flies", "flying", "flew", "flight", "sing", "sings", "singing", "song", "call", "calls",
    "calling", "dance", "dances", "dancing", "warning", "warn", "warns", "totem", "moiety", "sacred",
    "story", "story-site", "place", "place-name", "nest", "nests", "egg", "eggs", "feather", "feathers",
    "food", "eat", "eats", "ate", "eaten", "hunt", "hunting", "catch", "catches", "caught", "storm",
    "weather", "wood", "tree", "spirit", "messenger",
)


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 young cassowary is there.", "Barbarr yinyay.", "barbarr yinyay | young.cassowary there", "r174_deictic_barbarr_there", ["barbarr", "yinyay"], "Rule 174 consolidates barbarr as young cassowary with yinyay deictic support."),
    row(2, "The mudlark is there.", "Bayil-bayil yinyay.", "bayil-bayil yinyay | mudlark there", "r174_deictic_bayilbayil_there", ["bayil-bayil", "yinyay"], "Rule 174 consolidates bayil-bayil as mudlark; whole lexical head only."),
    row(3, "The spoon bill bird is there.", "Biluwarra yinyay.", "biluwarra yinyay | spoon.bill.bird there", "r174_deictic_biluwarra_there", ["biluwarra", "yinyay"], "Rule 174 consolidates biluwarra as spoon bill bird with deictic support."),
    row(4, "The scarlet robin is there.", "Binjul-binjul yinyay.", "binjul-binjul yinyay | scarlet.robin there", "r174_deictic_binjulbinjul_there", ["binjul-binjul", "yinyay"], "Rule 174 consolidates binjul-binjul as scarlet robin; no colour predicate."),
    row(5, "The willie wagtail is there.", "Dijarr-dijin yinyay.", "dijarr-dijin yinyay | willie.wagtail there", "r174_deictic_dijarrdijin_there", ["dijarr-dijin", "yinyay"], "Rule 174 consolidates dijarr-dijin as willie wagtail; no tail/body-part claim."),
    row(6, "The magpie is there.", "Kurburrubun yinyay.", "kurburrubun yinyay | magpie there", "r174_deictic_kurburrubun_there", ["kurburrubun", "yinyay"], "Rule 174 consolidates kurburrubun as magpie; reference only."),
    row(7, "The butcherbird is there.", "Kurkumbay yinyay.", "kurkumbay yinyay | butcherbird there", "r174_deictic_kurkumbay_there", ["kurkumbay", "yinyay"], "Rule 174 consolidates kurkumbay as butcherbird; no meat or song row."),
    row(8, "The bronze wing pigeon is there.", "Kurungka yinyay.", "kurungka yinyay | bronze.wing.pigeon there", "r174_deictic_kurungka_there", ["kurungka", "yinyay"], "Rule 174 consolidates kurungka as bronze wing pigeon; common-name wing is not body-part syntax."),
    row(9, "The dove is there.", "Munwingkul yinyay.", "munwingkul yinyay | dove there", "r174_deictic_munwingkul_there", ["munwingkul", "yinyay"], "Rule 174 consolidates munwingkul as dove; no habitat/flock row."),
    row(10, "The forest kingfisher is there.", "Yindili yinyay.", "yindili yinyay | forest.kingfisher there", "r174_deictic_yindili_there", ["yindili", "yinyay"], "Rule 174 consolidates yindili as forest kingfisher; no forest-place or fishing row."),
    row(11, "I see the young cassowary here.", "Ngayu barbarr yaluy nyajil.", "ngayu barbarr yaluy nyaji-l | I young.cassowary here see-NONPAST", "r174_present_i_barbarr_here", ["ngayu", "barbarr", "yaluy", "nyaji-l"], "First-person present perception with bare bird object and yaluy support."),
    row(12, "I see the mudlark here.", "Ngayu bayil-bayil yaluy nyajil.", "ngayu bayil-bayil yaluy nyaji-l | I mudlark here see-NONPAST", "r174_present_i_bayilbayil_here", ["ngayu", "bayil-bayil", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(13, "I see the spoon bill bird here.", "Ngayu biluwarra yaluy nyajil.", "ngayu biluwarra yaluy nyaji-l | I spoon.bill.bird here see-NONPAST", "r174_present_i_biluwarra_here", ["ngayu", "biluwarra", "yaluy", "nyaji-l"], "First-person present perception; no body-part bill claim."),
    row(14, "I see the scarlet robin here.", "Ngayu binjul-binjul yaluy nyajil.", "ngayu binjul-binjul yaluy nyaji-l | I scarlet.robin here see-NONPAST", "r174_present_i_binjulbinjul_here", ["ngayu", "binjul-binjul", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(15, "I see the willie wagtail here.", "Ngayu dijarr-dijin yaluy nyajil.", "ngayu dijarr-dijin yaluy nyaji-l | I willie.wagtail here see-NONPAST", "r174_present_i_dijarrdijin_here", ["ngayu", "dijarr-dijin", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(16, "I see the magpie here.", "Ngayu kurburrubun yaluy nyajil.", "ngayu kurburrubun yaluy nyaji-l | I magpie here see-NONPAST", "r174_present_i_kurburrubun_here", ["ngayu", "kurburrubun", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(17, "I see the butcherbird here.", "Ngayu kurkumbay yaluy nyajil.", "ngayu kurkumbay yaluy nyaji-l | I butcherbird here see-NONPAST", "r174_present_i_kurkumbay_here", ["ngayu", "kurkumbay", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(18, "I see the bronze wing pigeon here.", "Ngayu kurungka yaluy nyajil.", "ngayu kurungka yaluy nyaji-l | I bronze.wing.pigeon here see-NONPAST", "r174_present_i_kurungka_here", ["ngayu", "kurungka", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(19, "I see the dove here.", "Ngayu munwingkul yaluy nyajil.", "ngayu munwingkul yaluy nyaji-l | I dove here see-NONPAST", "r174_present_i_munwingkul_here", ["ngayu", "munwingkul", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(20, "I see the forest kingfisher here.", "Ngayu yindili yaluy nyajil.", "ngayu yindili yaluy nyaji-l | I forest.kingfisher here see-NONPAST", "r174_present_i_yindili_here", ["ngayu", "yindili", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(21, "You see the young cassowary here.", "Yundu barbarr yaluy nyajil.", "yundu barbarr yaluy nyaji-l | you young.cassowary here see-NONPAST", "r174_present_you_barbarr_here", ["yundu", "barbarr", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(22, "You see the mudlark here.", "Yundu bayil-bayil yaluy nyajil.", "yundu bayil-bayil yaluy nyaji-l | you mudlark here see-NONPAST", "r174_present_you_bayilbayil_here", ["yundu", "bayil-bayil", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(23, "You see the spoon bill bird here.", "Yundu biluwarra yaluy nyajil.", "yundu biluwarra yaluy nyaji-l | you spoon.bill.bird here see-NONPAST", "r174_present_you_biluwarra_here", ["yundu", "biluwarra", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(24, "You see the scarlet robin here.", "Yundu binjul-binjul yaluy nyajil.", "yundu binjul-binjul yaluy nyaji-l | you scarlet.robin here see-NONPAST", "r174_present_you_binjulbinjul_here", ["yundu", "binjul-binjul", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(25, "You see the willie wagtail here.", "Yundu dijarr-dijin yaluy nyajil.", "yundu dijarr-dijin yaluy nyaji-l | you willie.wagtail here see-NONPAST", "r174_present_you_dijarrdijin_here", ["yundu", "dijarr-dijin", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(26, "You see the magpie here.", "Yundu kurburrubun yaluy nyajil.", "yundu kurburrubun yaluy nyaji-l | you magpie here see-NONPAST", "r174_present_you_kurburrubun_here", ["yundu", "kurburrubun", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(27, "You see the butcherbird here.", "Yundu kurkumbay yaluy nyajil.", "yundu kurkumbay yaluy nyaji-l | you butcherbird here see-NONPAST", "r174_present_you_kurkumbay_here", ["yundu", "kurkumbay", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(28, "You see the bronze wing pigeon here.", "Yundu kurungka yaluy nyajil.", "yundu kurungka yaluy nyaji-l | you bronze.wing.pigeon here see-NONPAST", "r174_present_you_kurungka_here", ["yundu", "kurungka", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(29, "You see the dove here.", "Yundu munwingkul yaluy nyajil.", "yundu munwingkul yaluy nyaji-l | you dove here see-NONPAST", "r174_present_you_munwingkul_here", ["yundu", "munwingkul", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(30, "You see the forest kingfisher here.", "Yundu yindili yaluy nyajil.", "yundu yindili yaluy nyaji-l | you forest.kingfisher here see-NONPAST", "r174_present_you_yindili_here", ["yundu", "yindili", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(31, "They saw the young cassowary here.", "Jana barbarr yaluy nyajin.", "jana barbarr yaluy nyaji-ny | they young.cassowary here see-PAST", "r174_past_they_barbarr_here", ["jana", "barbarr", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(32, "They saw the mudlark here.", "Jana bayil-bayil yaluy nyajin.", "jana bayil-bayil yaluy nyaji-ny | they mudlark here see-PAST", "r174_past_they_bayilbayil_here", ["jana", "bayil-bayil", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(33, "They saw the spoon bill bird here.", "Jana biluwarra yaluy nyajin.", "jana biluwarra yaluy nyaji-ny | they spoon.bill.bird here see-PAST", "r174_past_they_biluwarra_here", ["jana", "biluwarra", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(34, "They saw the scarlet robin here.", "Jana binjul-binjul yaluy nyajin.", "jana binjul-binjul yaluy nyaji-ny | they scarlet.robin here see-PAST", "r174_past_they_binjulbinjul_here", ["jana", "binjul-binjul", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(35, "They saw the willie wagtail here.", "Jana dijarr-dijin yaluy nyajin.", "jana dijarr-dijin yaluy nyaji-ny | they willie.wagtail here see-PAST", "r174_past_they_dijarrdijin_here", ["jana", "dijarr-dijin", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(36, "They saw the magpie here.", "Jana kurburrubun yaluy nyajin.", "jana kurburrubun yaluy nyaji-ny | they magpie here see-PAST", "r174_past_they_kurburrubun_here", ["jana", "kurburrubun", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(37, "They saw the butcherbird here.", "Jana kurkumbay yaluy nyajin.", "jana kurkumbay yaluy nyaji-ny | they butcherbird here see-PAST", "r174_past_they_kurkumbay_here", ["jana", "kurkumbay", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(38, "They saw the bronze wing pigeon here.", "Jana kurungka yaluy nyajin.", "jana kurungka yaluy nyaji-ny | they bronze.wing.pigeon here see-PAST", "r174_past_they_kurungka_here", ["jana", "kurungka", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(39, "They saw the dove here.", "Jana munwingkul yaluy nyajin.", "jana munwingkul yaluy nyaji-ny | they dove here see-PAST", "r174_past_they_munwingkul_here", ["jana", "munwingkul", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(40, "They saw the forest kingfisher here.", "Jana yindili yaluy nyajin.", "jana yindili yaluy nyaji-ny | they forest.kingfisher here see-PAST", "r174_past_they_yindili_here", ["jana", "yindili", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(41, "We see the young cassowary there.", "Ngana barbarr yinyay nyajil.", "ngana barbarr yinyay nyaji-l | we young.cassowary there see-NONPAST", "r174_present_we_barbarr_there", ["ngana", "barbarr", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(42, "We see the mudlark there.", "Ngana bayil-bayil yinyay nyajil.", "ngana bayil-bayil yinyay nyaji-l | we mudlark there see-NONPAST", "r174_present_we_bayilbayil_there", ["ngana", "bayil-bayil", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(43, "We see the spoon bill bird there.", "Ngana biluwarra yinyay nyajil.", "ngana biluwarra yinyay nyaji-l | we spoon.bill.bird there see-NONPAST", "r174_present_we_biluwarra_there", ["ngana", "biluwarra", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(44, "We see the scarlet robin there.", "Ngana binjul-binjul yinyay nyajil.", "ngana binjul-binjul yinyay nyaji-l | we scarlet.robin there see-NONPAST", "r174_present_we_binjulbinjul_there", ["ngana", "binjul-binjul", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(45, "We see the willie wagtail there.", "Ngana dijarr-dijin yinyay nyajil.", "ngana dijarr-dijin yinyay nyaji-l | we willie.wagtail there see-NONPAST", "r174_present_we_dijarrdijin_there", ["ngana", "dijarr-dijin", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(46, "We see the magpie there.", "Ngana kurburrubun yinyay nyajil.", "ngana kurburrubun yinyay nyaji-l | we magpie there see-NONPAST", "r174_present_we_kurburrubun_there", ["ngana", "kurburrubun", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(47, "We see the butcherbird there.", "Ngana kurkumbay yinyay nyajil.", "ngana kurkumbay yinyay nyaji-l | we butcherbird there see-NONPAST", "r174_present_we_kurkumbay_there", ["ngana", "kurkumbay", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(48, "We see the bronze wing pigeon there.", "Ngana kurungka yinyay nyajil.", "ngana kurungka yinyay nyaji-l | we bronze.wing.pigeon there see-NONPAST", "r174_present_we_kurungka_there", ["ngana", "kurungka", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(49, "We see the dove there.", "Ngana munwingkul yinyay nyajil.", "ngana munwingkul yinyay nyaji-l | we dove there see-NONPAST", "r174_present_we_munwingkul_there", ["ngana", "munwingkul", "yinyay", "nyaji-l"], "Inclusive present perception; target object bare."),
    row(50, "We see the forest kingfisher there.", "Ngana yindili yinyay nyajil.", "ngana yindili yinyay nyaji-l | we forest.kingfisher there see-NONPAST", "r174_present_we_yindili_there", ["ngana", "yindili", "yinyay", "nyaji-l"], "Inclusive present perception; target object 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("r174_"):
            issues.append(f"{label}: Rule 174 frame must start with r174_")
        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 174")
        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 173 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 and selected 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 174 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 174 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 bird 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 174 draft: construction consolidation after Rule 173", "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 174 source pass retained exactly the ten Rule 173 bird-reference heads: barbarr, bayil-bayil, biluwarra, binjul-binjul, dijarr-dijin, kurburrubun, kurkumbay, kurungka, munwingkul, and yindili. 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 215 accepted rows and zero Batch 216 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 174 is a construction consolidation pass for the Rule 173 bird-reference field. It admits no new bird heads and excludes flying, singing, calling, dancing, warning, totem/moiety, sacred-bird, story-site, nest, egg, feather, food, eating, hunting, catching, storm, place, wood, secondary-sense, 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_216.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 173 bird target per row; all targets bare; no loans; no rejected-bird/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_216.py static scan", artifact_path="batch_scripts/bank_216.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())
