#!/usr/bin/env python3
"""Bank batch-212: Rule 170 construction consolidation after Rule 169."""

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

TARGET_HEADS = {
    "biray": "grey march fly",
    "kamay": "yellow march fly",
    "manukurru": "scorpion",
    "mindil": "dog flea",
    "murrmun": "rhinoceros beetle",
    "murrumun": "black beetle",
    "muyu-muyu": "small red ant",
    "wurrarr-wurrarr": "mud wasp",
    "yijil-yijin": "cricket",
    "yinja-yinja": "cicada",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "bayka", "baykal", "baykan", "yinbay", "yungka", "yungal", "nuka", "nukan", "waju", "wajun",
    "mani", "manin", "daji", "dajin", "dunga", "dungan", "wandi", "wandin", "baya", "kubu", "bubu",
    "diri-diri", "wurarr-wurarr", "kamu", "jimu", "kinga", "birinjil", "kandal", "mulma", "dabu",
    "kuja", "malal", "nyumbil", "waja", "walbul-walbul", "wunba", "yangka", "kalkamal", "karrkil",
    "kuran", "ngirran", "nyirran",
}
DENY_ENGLISH = (
    "bite", "bites", "bit", "biting", "sting", "stings", "stung", "sick", "sickness", "vomit", "vomited",
    "honey", "nest", "nests", "egg", "eggs", "larva", "larvae", "edible", "eat", "eats", "ate", "food",
    "medicine", "heal", "healed", "season", "seasonal", "totem", "moiety", "life force", "crow", "stingray",
    "flying fish", "mangrove", "store", "swarm", "swarmed", "pest", "control", "danger", "dangerous",
)


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 grey March fly is there.", "Biray yinyay.", "biray yinyay | grey.march.fly there", "r170_deictic_biray_there", ["biray", "yinyay"], "Rule 170 retains Rule 169 biray as grey March fly; bare yinyay deictic consolidation."),
    row(2, "The yellow March fly is there.", "Kamay yinyay.", "kamay yinyay | yellow.march.fly there", "r170_deictic_kamay_there", ["kamay", "yinyay"], "Rule 170 retains Rule 169 kamay as yellow March fly; bare yinyay deictic consolidation."),
    row(3, "The scorpion is there.", "Manukurru yinyay.", "manukurru yinyay | scorpion there", "r170_deictic_manukurru_there", ["manukurru", "yinyay"], "Rule 170 retains Rule 169 manukurru as scorpion; no sting/danger row."),
    row(4, "The dog flea is there.", "Mindil yinyay.", "mindil yinyay | dog.flea there", "r170_deictic_mindil_there", ["mindil", "yinyay"], "Rule 170 retains Rule 169 mindil as dog flea; reference only."),
    row(5, "The rhinoceros beetle is there.", "Murrmun yinyay.", "murrmun yinyay | rhinoceros.beetle there", "r170_deictic_murrmun_there", ["murrmun", "yinyay"], "Rule 170 retains Rule 169 murrmun as rhinoceros beetle; no grub/life-stage row."),
    row(6, "The black beetle is there.", "Murrumun yinyay.", "murrumun yinyay | black.beetle there", "r170_deictic_murrumun_there", ["murrumun", "yinyay"], "Rule 170 retains Rule 169 murrumun as black beetle; reference only."),
    row(7, "The small red ant is there.", "Muyu-muyu yinyay.", "muyu-muyu yinyay | small.red.ant there", "r170_deictic_muyumuyu_there", ["muyu-muyu", "yinyay"], "Rule 170 retains Rule 169 muyu-muyu as small red ant; whole lexical head."),
    row(8, "The mud wasp is there.", "Wurrarr-wurrarr yinyay.", "wurrarr-wurrarr yinyay | mud.wasp there", "r170_deictic_wurrarrwurrarr_there", ["wurrarr-wurrarr", "yinyay"], "Rule 170 retains Rule 169 wurrarr-wurrarr as mud wasp; no sting/nest row."),
    row(9, "The cricket is there.", "Yijil-yijin yinyay.", "yijil-yijin yinyay | cricket there", "r170_deictic_yijilyijin_there", ["yijil-yijin", "yinyay"], "Rule 170 retains Rule 169 yijil-yijin as cricket; whole lexical head."),
    row(10, "The cicada is there.", "Yinja-yinja yinyay.", "yinja-yinja yinyay | cicada there", "r170_deictic_yinjayinja_there", ["yinja-yinja", "yinyay"], "Rule 170 retains Rule 169 yinja-yinja as cicada; whole lexical head."),
    row(11, "I see the grey March fly here.", "Ngayu biray yaluy nyajil.", "ngayu biray yaluy nyaji-l | I grey.march.fly here see-NONPAST", "r170_present_i_biray_here", ["ngayu", "biray", "yaluy", "nyaji-l"], "Pronoun A bare; biray object bare; yaluy support only."),
    row(12, "I see the yellow March fly here.", "Ngayu kamay yaluy nyajil.", "ngayu kamay yaluy nyaji-l | I yellow.march.fly here see-NONPAST", "r170_present_i_kamay_here", ["ngayu", "kamay", "yaluy", "nyaji-l"], "Pronoun A bare; kamay object bare; yaluy support only."),
    row(13, "I see the scorpion here.", "Ngayu manukurru yaluy nyajil.", "ngayu manukurru yaluy nyaji-l | I scorpion here see-NONPAST", "r170_present_i_manukurru_here", ["ngayu", "manukurru", "yaluy", "nyaji-l"], "Pronoun A bare; no sting/danger row."),
    row(14, "I see the dog flea here.", "Ngayu mindil yaluy nyajil.", "ngayu mindil yaluy nyaji-l | I dog.flea here see-NONPAST", "r170_present_i_mindil_here", ["ngayu", "mindil", "yaluy", "nyaji-l"], "Pronoun A bare; mindil object bare."),
    row(15, "I see the rhinoceros beetle here.", "Ngayu murrmun yaluy nyajil.", "ngayu murrmun yaluy nyaji-l | I rhinoceros.beetle here see-NONPAST", "r170_present_i_murrmun_here", ["ngayu", "murrmun", "yaluy", "nyaji-l"], "Pronoun A bare; murrmun object bare."),
    row(16, "I see the black beetle here.", "Ngayu murrumun yaluy nyajil.", "ngayu murrumun yaluy nyaji-l | I black.beetle here see-NONPAST", "r170_present_i_murrumun_here", ["ngayu", "murrumun", "yaluy", "nyaji-l"], "Pronoun A bare; murrumun object bare."),
    row(17, "I see the small red ant here.", "Ngayu muyu-muyu yaluy nyajil.", "ngayu muyu-muyu yaluy nyaji-l | I small.red.ant here see-NONPAST", "r170_present_i_muyumuyu_here", ["ngayu", "muyu-muyu", "yaluy", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(18, "I see the mud wasp here.", "Ngayu wurrarr-wurrarr yaluy nyajil.", "ngayu wurrarr-wurrarr yaluy nyaji-l | I mud.wasp here see-NONPAST", "r170_present_i_wurrarrwurrarr_here", ["ngayu", "wurrarr-wurrarr", "yaluy", "nyaji-l"], "Pronoun A bare; no sting/nest row."),
    row(19, "I see the cricket here.", "Ngayu yijil-yijin yaluy nyajil.", "ngayu yijil-yijin yaluy nyaji-l | I cricket here see-NONPAST", "r170_present_i_yijilyijin_here", ["ngayu", "yijil-yijin", "yaluy", "nyaji-l"], "Pronoun A bare; yijil-yijin object bare."),
    row(20, "I see the cicada here.", "Ngayu yinja-yinja yaluy nyajil.", "ngayu yinja-yinja yaluy nyaji-l | I cicada here see-NONPAST", "r170_present_i_yinjayinja_here", ["ngayu", "yinja-yinja", "yaluy", "nyaji-l"], "Pronoun A bare; yinja-yinja object bare."),
    row(21, "You see the grey March fly here.", "Yundu biray yaluy nyajil.", "yundu biray yaluy nyaji-l | you grey.march.fly here see-NONPAST", "r170_present_you_biray_here", ["yundu", "biray", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support only."),
    row(22, "You see the yellow March fly here.", "Yundu kamay yaluy nyajil.", "yundu kamay yaluy nyaji-l | you yellow.march.fly here see-NONPAST", "r170_present_you_kamay_here", ["yundu", "kamay", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support only."),
    row(23, "You see the scorpion here.", "Yundu manukurru yaluy nyajil.", "yundu manukurru yaluy nyaji-l | you scorpion here see-NONPAST", "r170_present_you_manukurru_here", ["yundu", "manukurru", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no sting/danger row."),
    row(24, "You see the dog flea here.", "Yundu mindil yaluy nyajil.", "yundu mindil yaluy nyaji-l | you dog.flea here see-NONPAST", "r170_present_you_mindil_here", ["yundu", "mindil", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(25, "You see the rhinoceros beetle here.", "Yundu murrmun yaluy nyajil.", "yundu murrmun yaluy nyaji-l | you rhinoceros.beetle here see-NONPAST", "r170_present_you_murrmun_here", ["yundu", "murrmun", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the black beetle here.", "Yundu murrumun yaluy nyajil.", "yundu murrumun yaluy nyaji-l | you black.beetle here see-NONPAST", "r170_present_you_murrumun_here", ["yundu", "murrumun", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the small red ant here.", "Yundu muyu-muyu yaluy nyajil.", "yundu muyu-muyu yaluy nyaji-l | you small.red.ant here see-NONPAST", "r170_present_you_muyumuyu_here", ["yundu", "muyu-muyu", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the mud wasp here.", "Yundu wurrarr-wurrarr yaluy nyajil.", "yundu wurrarr-wurrarr yaluy nyaji-l | you mud.wasp here see-NONPAST", "r170_present_you_wurrarrwurrarr_here", ["yundu", "wurrarr-wurrarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no sting/nest row."),
    row(29, "You see the cricket here.", "Yundu yijil-yijin yaluy nyajil.", "yundu yijil-yijin yaluy nyaji-l | you cricket here see-NONPAST", "r170_present_you_yijilyijin_here", ["yundu", "yijil-yijin", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the cicada here.", "Yundu yinja-yinja yaluy nyajil.", "yundu yinja-yinja yaluy nyaji-l | you cicada here see-NONPAST", "r170_present_you_yinjayinja_here", ["yundu", "yinja-yinja", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the grey March fly here.", "Jana biray yaluy nyajin.", "jana biray yaluy nyaji-ny | they grey.march.fly here see-PAST", "r170_past_they_biray_here", ["jana", "biray", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception; yaluy support only."),
    row(32, "They saw the yellow March fly here.", "Jana kamay yaluy nyajin.", "jana kamay yaluy nyaji-ny | they yellow.march.fly here see-PAST", "r170_past_they_kamay_here", ["jana", "kamay", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception; target bare."),
    row(33, "They saw the scorpion here.", "Jana manukurru yaluy nyajin.", "jana manukurru yaluy nyaji-ny | they scorpion here see-PAST", "r170_past_they_manukurru_here", ["jana", "manukurru", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no sting/danger row."),
    row(34, "They saw the dog flea here.", "Jana mindil yaluy nyajin.", "jana mindil yaluy nyaji-ny | they dog.flea here see-PAST", "r170_past_they_mindil_here", ["jana", "mindil", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(35, "They saw the rhinoceros beetle here.", "Jana murrmun yaluy nyajin.", "jana murrmun yaluy nyaji-ny | they rhinoceros.beetle here see-PAST", "r170_past_they_murrmun_here", ["jana", "murrmun", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(36, "They saw the black beetle here.", "Jana murrumun yaluy nyajin.", "jana murrumun yaluy nyaji-ny | they black.beetle here see-PAST", "r170_past_they_murrumun_here", ["jana", "murrumun", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(37, "They saw the small red ant here.", "Jana muyu-muyu yaluy nyajin.", "jana muyu-muyu yaluy nyaji-ny | they small.red.ant here see-PAST", "r170_past_they_muyumuyu_here", ["jana", "muyu-muyu", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(38, "They saw the mud wasp here.", "Jana wurrarr-wurrarr yaluy nyajin.", "jana wurrarr-wurrarr yaluy nyaji-ny | they mud.wasp here see-PAST", "r170_past_they_wurrarrwurrarr_here", ["jana", "wurrarr-wurrarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no sting/nest row."),
    row(39, "They saw the cricket here.", "Jana yijil-yijin yaluy nyajin.", "jana yijil-yijin yaluy nyaji-ny | they cricket here see-PAST", "r170_past_they_yijilyijin_here", ["jana", "yijil-yijin", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(40, "They saw the cicada here.", "Jana yinja-yinja yaluy nyajin.", "jana yinja-yinja yaluy nyaji-ny | they cicada here see-PAST", "r170_past_they_yinjayinja_here", ["jana", "yinja-yinja", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(41, "We see the grey March fly there.", "Ngana biray yinyay nyajil.", "ngana biray yinyay nyaji-l | we grey.march.fly there see-NONPAST", "r170_present_we_biray_there", ["ngana", "biray", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support only."),
    row(42, "We see the yellow March fly there.", "Ngana kamay yinyay nyajil.", "ngana kamay yinyay nyaji-l | we yellow.march.fly there see-NONPAST", "r170_present_we_kamay_there", ["ngana", "kamay", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support only."),
    row(43, "We see the scorpion there.", "Ngana manukurru yinyay nyajil.", "ngana manukurru yinyay nyaji-l | we scorpion there see-NONPAST", "r170_present_we_manukurru_there", ["ngana", "manukurru", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no sting/danger row."),
    row(44, "We see the dog flea there.", "Ngana mindil yinyay nyajil.", "ngana mindil yinyay nyaji-l | we dog.flea there see-NONPAST", "r170_present_we_mindil_there", ["ngana", "mindil", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(45, "We see the rhinoceros beetle there.", "Ngana murrmun yinyay nyajil.", "ngana murrmun yinyay nyaji-l | we rhinoceros.beetle there see-NONPAST", "r170_present_we_murrmun_there", ["ngana", "murrmun", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(46, "We see the black beetle there.", "Ngana murrumun yinyay nyajil.", "ngana murrumun yinyay nyaji-l | we black.beetle there see-NONPAST", "r170_present_we_murrumun_there", ["ngana", "murrumun", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(47, "We see the small red ant there.", "Ngana muyu-muyu yinyay nyajil.", "ngana muyu-muyu yinyay nyaji-l | we small.red.ant there see-NONPAST", "r170_present_we_muyumuyu_there", ["ngana", "muyu-muyu", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(48, "We see the mud wasp there.", "Ngana wurrarr-wurrarr yinyay nyajil.", "ngana wurrarr-wurrarr yinyay nyaji-l | we mud.wasp there see-NONPAST", "r170_present_we_wurrarrwurrarr_there", ["ngana", "wurrarr-wurrarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no sting/nest row."),
    row(49, "We see the cricket there.", "Ngana yijil-yijin yinyay nyajil.", "ngana yijil-yijin yinyay nyaji-l | we cricket there see-NONPAST", "r170_present_we_yijilyijin_there", ["ngana", "yijil-yijin", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(50, "We see the cicada there.", "Ngana yinja-yinja yinyay nyajil.", "ngana yinja-yinja yinyay nyaji-l | we cicada there see-NONPAST", "r170_present_we_yinjayinja_there", ["ngana", "yinja-yinja", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; 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("r170_"):
            issues.append(f"{label}: Rule 170 frame must start with r170_")
        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 170")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied rejected-insect/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 170 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 170 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 170 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 "here" not in english_low or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yaluy/here + 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 use/event/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 170 draft: construction consolidation after Rule 169", "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 170 source pass retained the Rule 169 insect heads biray, kamay, manukurru, mindil, murrmun, murrumun, muyu-muyu, wurrarr-wurrarr, yijil-yijin, and yinja-yinja. Dictionary exact readback reconfirmed selected senses. Patz readback found no target-head conflicts and reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Boundary-aware corpus readback found only the clean Batch 211 reference/perception rows for the selected targets.",
                 command="rg dictionary exact 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="construction-scope", actor="claude-main",
                 detail="Rule 170 is construction consolidation over the Rule 169 insect-reference set. It uses bare target heads only and rotates yinyay/yaluy support across deictic and perception frames. It excludes biting, stinging, sickness, honey, nests, eggs, larvae, edible use, medicine, totem/moiety, life-force, seasonal signal, ecology, movement, danger, pest-control, 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_212.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 Rule 170 insect target per row; all targets bare; no loans; no rejected-insect/use/event/polysemy tokens; no target case/compound forms; yinyay deictic rows; yaluy-supported ngayu/yundu/jana perception rows; yinyay-supported ngana perception rows.",
                 command="python3 batch_scripts/bank_212.py static scan", artifact_path="batch_scripts/bank_212.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())
