#!/usr/bin/env python3
"""Bank batch-202: Rule 160 construction consolidation after Rule 159."""

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

TARGET_HEADS = {
    "babi": "grandmother",
    "kami": "grandfather",
    "kalnga": "mother's.brother",
    "bimakay": "father's.sister",
    "ngaji": "mother's.father",
    "jija": "son's.child",
    "kaminjarr": "daughter's.child",
    "kangkal": "own.child",
    "yaba": "older.brother",
    "babarr": "older.sister",
}
TARGET_ENGLISH = {
    "babi": "grandmother",
    "kami": "grandfather",
    "kalnga": "mother's brother",
    "bimakay": "father's sister",
    "ngaji": "mother's father",
    "jija": "son's child",
    "kaminjarr": "daughter's child",
    "kangkal": "son or daughter",
    "yaba": "older brother",
    "babarr": "older sister",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "dunga", "dungan", "kada", "kadan", "bunda", "bundan", "wuna", "wunan", "balkan", "balka", "balka-l",
    "babaji", "babajin", "kunja", "kunjan", "kuni", "kunin", "nuka", "nukan", "waju", "wajun", "mani",
    "manin", "daji", "dajin", "wundi", "wundin", "baka", "bakan", "yajarri", "yajarrin", "ngara", "ngaran",
    "dama", "daman", "nyaji-l-nyaji", "yaba-karra", "babarr-karra", "manyarr-karra", "kangkal-kangkal",
    "yaba-nji", "babarr-andamun", "ngamu-karra", "nganjan-karra",
}
DENY_ENGLISH = (
    "go", "went", "come", "came", "sit", "sitting", "stand", "standing", "sleep", "sleeping", "ask", "asked",
    "call", "called", "talk", "speak", "spoke", "hit", "fight", "fighting", "kill", "killed", "bite", "bit",
    "eat", "ate", "food", "cook", "cooked", "hunt", "hunting", "work", "teach", "teaching", "learn", "marry",
    "married", "wife", "relative", "relations", "with a friend", "many", "crowd", "eel", "cassowary",
)


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 grandmother is here.", "Babi yaluy.", "babi yaluy | grandmother here", "r160_deictic_grandmother_here", ["babi", "yaluy"], "Rule 160 consolidates babi in a bare yaluy deictic frame."),
    row(2, "The grandfather is here.", "Kami yaluy.", "kami yaluy | grandfather here", "r160_deictic_grandfather_here", ["kami", "yaluy"], "Bare target plus yaluy; no event semantics."),
    row(3, "The mother's brother is here.", "Kalnga yaluy.", "kalnga yaluy | mother's.brother here", "r160_deictic_mothers_brother_here", ["kalnga", "yaluy"], "Bare target plus yaluy; no possessive morphology."),
    row(4, "The father's sister is here.", "Bimakay yaluy.", "bimakay yaluy | father's.sister here", "r160_deictic_fathers_sister_here", ["bimakay", "yaluy"], "Bare target plus yaluy; no address/event row."),
    row(5, "The mother's father is here.", "Ngaji yaluy.", "ngaji yaluy | mother's.father here", "r160_deictic_mothers_father_here", ["ngaji", "yaluy"], "Bare target plus yaluy; no death/season row."),
    row(6, "The son's child is here.", "Jija yaluy.", "jija yaluy | son's.child here", "r160_deictic_sons_child_here", ["jija", "yaluy"], "Bare target plus yaluy; no plural/possession."),
    row(7, "The daughter's child is here.", "Kaminjarr yaluy.", "kaminjarr yaluy | daughter's.child here", "r160_deictic_daughters_child_here", ["kaminjarr", "yaluy"], "Bare target plus yaluy; no plural/possession."),
    row(8, "The son or daughter is here.", "Kangkal yaluy.", "kangkal yaluy | own.child here", "r160_deictic_own_child_here", ["kangkal", "yaluy"], "Bare target plus yaluy; own-child sense only."),
    row(9, "The older brother is here.", "Yaba yaluy.", "yaba yaluy | older.brother here", "r160_deictic_older_brother_here", ["yaba", "yaluy"], "Bare target plus yaluy; eel homograph closed."),
    row(10, "The older sister is here.", "Babarr yaluy.", "babarr yaluy | older.sister here", "r160_deictic_older_sister_here", ["babarr", "yaluy"], "Bare target plus yaluy; cassowary homograph closed."),
    row(11, "I see the grandmother there.", "Ngayu babi yinyay nyajil.", "ngayu babi yinyay nyaji-l | I grandmother there see-NONPAST", "r160_present_i_grandmother_there", ["ngayu", "babi", "yinyay", "nyaji-l"], "Pronoun A bare; yinyay support only."),
    row(12, "I see the grandfather there.", "Ngayu kami yinyay nyajil.", "ngayu kami yinyay nyaji-l | I grandfather there see-NONPAST", "r160_present_i_grandfather_there", ["ngayu", "kami", "yinyay", "nyaji-l"], "Pronoun A bare; yinyay support only."),
    row(13, "I see the mother's brother there.", "Ngayu kalnga yinyay nyajil.", "ngayu kalnga yinyay nyaji-l | I mother's.brother there see-NONPAST", "r160_present_i_mothers_brother_there", ["ngayu", "kalnga", "yinyay", "nyaji-l"], "Pronoun A bare; no authority/teaching import."),
    row(14, "I see the father's sister there.", "Ngayu bimakay yinyay nyajil.", "ngayu bimakay yinyay nyaji-l | I father's.sister there see-NONPAST", "r160_present_i_fathers_sister_there", ["ngayu", "bimakay", "yinyay", "nyaji-l"], "Pronoun A bare; no address/event row."),
    row(15, "I see the mother's father there.", "Ngayu ngaji yinyay nyajil.", "ngayu ngaji yinyay nyaji-l | I mother's.father there see-NONPAST", "r160_present_i_mothers_father_there", ["ngayu", "ngaji", "yinyay", "nyaji-l"], "Pronoun A bare; no death/season row."),
    row(16, "I see the son's child there.", "Ngayu jija yinyay nyajil.", "ngayu jija yinyay nyaji-l | I son's.child there see-NONPAST", "r160_present_i_sons_child_there", ["ngayu", "jija", "yinyay", "nyaji-l"], "Pronoun A bare; no plural/possession."),
    row(17, "I see the daughter's child there.", "Ngayu kaminjarr yinyay nyajil.", "ngayu kaminjarr yinyay nyaji-l | I daughter's.child there see-NONPAST", "r160_present_i_daughters_child_there", ["ngayu", "kaminjarr", "yinyay", "nyaji-l"], "Pronoun A bare; no plural/possession."),
    row(18, "I see the son or daughter there.", "Ngayu kangkal yinyay nyajil.", "ngayu kangkal yinyay nyaji-l | I own.child there see-NONPAST", "r160_present_i_own_child_there", ["ngayu", "kangkal", "yinyay", "nyaji-l"], "Pronoun A bare; own-child sense only."),
    row(19, "I see the older brother there.", "Ngayu yaba yinyay nyajil.", "ngayu yaba yinyay nyaji-l | I older.brother there see-NONPAST", "r160_present_i_older_brother_there", ["ngayu", "yaba", "yinyay", "nyaji-l"], "Pronoun A bare; eel homograph closed."),
    row(20, "I see the older sister there.", "Ngayu babarr yinyay nyajil.", "ngayu babarr yinyay nyaji-l | I older.sister there see-NONPAST", "r160_present_i_older_sister_there", ["ngayu", "babarr", "yinyay", "nyaji-l"], "Pronoun A bare; cassowary homograph closed."),
    row(21, "You see the grandmother here.", "Yundu babi yaluy nyajil.", "yundu babi yaluy nyaji-l | you grandmother here see-NONPAST", "r160_present_you_grandmother_here", ["yundu", "babi", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support."),
    row(22, "You see the grandfather here.", "Yundu kami yaluy nyajil.", "yundu kami yaluy nyaji-l | you grandfather here see-NONPAST", "r160_present_you_grandfather_here", ["yundu", "kami", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support."),
    row(23, "You see the mother's brother here.", "Yundu kalnga yaluy nyajil.", "yundu kalnga yaluy nyaji-l | you mother's.brother here see-NONPAST", "r160_present_you_mothers_brother_here", ["yundu", "kalnga", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no authority/teaching import."),
    row(24, "You see the father's sister here.", "Yundu bimakay yaluy nyajil.", "yundu bimakay yaluy nyaji-l | you father's.sister here see-NONPAST", "r160_present_you_fathers_sister_here", ["yundu", "bimakay", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no address/event row."),
    row(25, "You see the mother's father here.", "Yundu ngaji yaluy nyajil.", "yundu ngaji yaluy nyaji-l | you mother's.father here see-NONPAST", "r160_present_you_mothers_father_here", ["yundu", "ngaji", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no death/season row."),
    row(26, "You see the son's child here.", "Yundu jija yaluy nyajil.", "yundu jija yaluy nyaji-l | you son's.child here see-NONPAST", "r160_present_you_sons_child_here", ["yundu", "jija", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no plural/possession."),
    row(27, "You see the daughter's child here.", "Yundu kaminjarr yaluy nyajil.", "yundu kaminjarr yaluy nyaji-l | you daughter's.child here see-NONPAST", "r160_present_you_daughters_child_here", ["yundu", "kaminjarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no plural/possession."),
    row(28, "You see the son or daughter here.", "Yundu kangkal yaluy nyajil.", "yundu kangkal yaluy nyaji-l | you own.child here see-NONPAST", "r160_present_you_own_child_here", ["yundu", "kangkal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; own-child sense only."),
    row(29, "You see the older brother here.", "Yundu yaba yaluy nyajil.", "yundu yaba yaluy nyaji-l | you older.brother here see-NONPAST", "r160_present_you_older_brother_here", ["yundu", "yaba", "yaluy", "nyaji-l"], "Second-person pronoun A bare; eel homograph closed."),
    row(30, "You see the older sister here.", "Yundu babarr yaluy nyajil.", "yundu babarr yaluy nyaji-l | you older.sister here see-NONPAST", "r160_present_you_older_sister_here", ["yundu", "babarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; cassowary homograph closed."),
    row(31, "They saw the grandmother here.", "Jana babi yaluy nyajin.", "jana babi yaluy nyaji-ny | they grandmother here see-PAST", "r160_past_they_grandmother_here", ["jana", "babi", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the grandfather here.", "Jana kami yaluy nyajin.", "jana kami yaluy nyaji-ny | they grandfather here see-PAST", "r160_past_they_grandfather_here", ["jana", "kami", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(33, "They saw the mother's brother here.", "Jana kalnga yaluy nyajin.", "jana kalnga yaluy nyaji-ny | they mother's.brother here see-PAST", "r160_past_they_mothers_brother_here", ["jana", "kalnga", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(34, "They saw the father's sister here.", "Jana bimakay yaluy nyajin.", "jana bimakay yaluy nyaji-ny | they father's.sister here see-PAST", "r160_past_they_fathers_sister_here", ["jana", "bimakay", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(35, "They saw the mother's father here.", "Jana ngaji yaluy nyajin.", "jana ngaji yaluy nyaji-ny | they mother's.father here see-PAST", "r160_past_they_mothers_father_here", ["jana", "ngaji", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(36, "They saw the son's child here.", "Jana jija yaluy nyajin.", "jana jija yaluy nyaji-ny | they son's.child here see-PAST", "r160_past_they_sons_child_here", ["jana", "jija", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(37, "They saw the daughter's child here.", "Jana kaminjarr yaluy nyajin.", "jana kaminjarr yaluy nyaji-ny | they daughter's.child here see-PAST", "r160_past_they_daughters_child_here", ["jana", "kaminjarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(38, "They saw the son or daughter here.", "Jana kangkal yaluy nyajin.", "jana kangkal yaluy nyaji-ny | they own.child here see-PAST", "r160_past_they_own_child_here", ["jana", "kangkal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; own-child sense only."),
    row(39, "They saw the older brother here.", "Jana yaba yaluy nyajin.", "jana yaba yaluy nyaji-ny | they older.brother here see-PAST", "r160_past_they_older_brother_here", ["jana", "yaba", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; eel homograph closed."),
    row(40, "They saw the older sister here.", "Jana babarr yaluy nyajin.", "jana babarr yaluy nyaji-ny | they older.sister here see-PAST", "r160_past_they_older_sister_here", ["jana", "babarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; cassowary homograph closed."),
    row(41, "We see the grandmother there.", "Ngana babi yinyay nyajil.", "ngana babi yinyay nyaji-l | we grandmother there see-NONPAST", "r160_present_we_grandmother_there", ["ngana", "babi", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support."),
    row(42, "We see the grandfather there.", "Ngana kami yinyay nyajil.", "ngana kami yinyay nyaji-l | we grandfather there see-NONPAST", "r160_present_we_grandfather_there", ["ngana", "kami", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support."),
    row(43, "We see the mother's brother there.", "Ngana kalnga yinyay nyajil.", "ngana kalnga yinyay nyaji-l | we mother's.brother there see-NONPAST", "r160_present_we_mothers_brother_there", ["ngana", "kalnga", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no authority/teaching import."),
    row(44, "We see the father's sister there.", "Ngana bimakay yinyay nyajil.", "ngana bimakay yinyay nyaji-l | we father's.sister there see-NONPAST", "r160_present_we_fathers_sister_there", ["ngana", "bimakay", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no address/event row."),
    row(45, "We see the mother's father there.", "Ngana ngaji yinyay nyajil.", "ngana ngaji yinyay nyaji-l | we mother's.father there see-NONPAST", "r160_present_we_mothers_father_there", ["ngana", "ngaji", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no death/season row."),
    row(46, "We see the son's child there.", "Ngana jija yinyay nyajil.", "ngana jija yinyay nyaji-l | we son's.child there see-NONPAST", "r160_present_we_sons_child_there", ["ngana", "jija", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no plural/possession."),
    row(47, "We see the daughter's child there.", "Ngana kaminjarr yinyay nyajil.", "ngana kaminjarr yinyay nyaji-l | we daughter's.child there see-NONPAST", "r160_present_we_daughters_child_there", ["ngana", "kaminjarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no plural/possession."),
    row(48, "We see the son or daughter there.", "Ngana kangkal yinyay nyajil.", "ngana kangkal yinyay nyaji-l | we own.child there see-NONPAST", "r160_present_we_own_child_there", ["ngana", "kangkal", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; own-child sense only."),
    row(49, "We see the older brother there.", "Ngana yaba yinyay nyajil.", "ngana yaba yinyay nyaji-l | we older.brother there see-NONPAST", "r160_present_we_older_brother_there", ["ngana", "yaba", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; eel homograph closed."),
    row(50, "We see the older sister there.", "Ngana babarr yinyay nyajil.", "ngana babarr yinyay nyaji-l | we older.sister there see-NONPAST", "r160_present_we_older_sister_there", ["ngana", "babarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; cassowary homograph closed."),
]


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


def english_has_denied(english_low: str, denied: str) -> bool:
    if " " in denied:
        return denied in english_low
    return 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("r160_"):
            issues.append(f"{label}: Rule 160 frame must start with r160_")
        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 new loans are admitted in Rule 160")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied extended-kin event/form 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 160 target head, found {targets}")
        for head in targets:
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if TARGET_HEADS[head] not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {TARGET_HEADS[head]}")
            if TARGET_ENGLISH[head] not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {TARGET_ENGLISH[head]!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if has_token(low, "yaba") and "older brother" not in english_low:
            issues.append(f"{label}: yaba must be older brother, not eel")
        if has_token(low, "babarr") and "older sister" not in english_low:
            issues.append(f"{label}: babarr must be older sister, not cassowary")
        if has_token(low, "kangkal") and "son or daughter" not in english_low:
            issues.append(f"{label}: kangkal must be own-child/son-or-daughter sense")
        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 160 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 160 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, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 11-20 require ngayu + yinyay/there")
            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 extended-kin event 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 160 draft: construction consolidation after Rule 159", "operator-guide-2026-07-07", "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 160 source pass retained the Rule 159 extended-kin targets babi, kami, kalnga, bimakay, ngaji, jija, kaminjarr, kangkal, yaba, and babarr; support forms yinyay, yaluy, nyaji-l; and bare pronoun A forms ngayu, yundu, jana, and ngana. Dictionary, Patz grammar, and lexeme-table readback completed.",
                 command="dictionary.yaml exact readback; grammar.md kin noun/pronoun/deictic/nyaji readback; sqlite lexeme 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 160 is a construction consolidation pass for bare yaluy deictic identification and deictic-supported perception frames. It excludes target case forms, compounds, possessives, kin plurals, address forms, marriage/change-of-state, avoidance, travel, food, conflict, work, teaching, asking, homograph animal senses, and social-event semantics.",
                 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_202.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: one bare extended-kin target per row, selected English senses enforced, no target case or compound morphology, no kin/social-event predicates, no action import, homograph traps closed, yinyay/yaluy support checked, and pronoun A bare.",
                 command="python3 batch_scripts/bank_202.py static scan", artifact_path="batch_scripts/bank_202.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, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, "claude-main", NOW, NOW)
         for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS],
    )
    record_event(db, batch_label=LABEL, phase="bank", event_type="bank-success", actor="claude-main",
                 detail="Banked 50 under_review Rule 160 extended-kin construction-consolidation rows.",
                 command="python3 batch_scripts/bank_202.py", artifact_path="batch_scripts/bank_202.py", created_at=NOW)
    db.commit()

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


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