#!/usr/bin/env python3
"""Bank batch-201: Rule 159 extended-kin reference lexical expansion after Rule 158."""

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-201"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-201-extended-kin-reference-lexical-expansion-after-rule158-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 there.", "Babi yinyay.", "babi yinyay | grandmother there", "r159_deictic_grandmother_there", ["babi", "yinyay"], "Dictionary/Patz babi grandmother; bare deictic only."),
    row(2, "The grandfather is there.", "Kami yinyay.", "kami yinyay | grandfather there", "r159_deictic_grandfather_there", ["kami", "yinyay"], "Dictionary/Patz kami grandfather; bare deictic only."),
    row(3, "The mother's brother is there.", "Kalnga yinyay.", "kalnga yinyay | mother's.brother there", "r159_deictic_mothers_brother_there", ["kalnga", "yinyay"], "Dictionary/Patz kalnga mother's brother; no possessive morphology."),
    row(4, "The father's sister is there.", "Bimakay yinyay.", "bimakay yinyay | father's.sister there", "r159_deictic_fathers_sister_there", ["bimakay", "yinyay"], "Dictionary/Patz bimakay father's sister; bare target."),
    row(5, "The mother's father is there.", "Ngaji yinyay.", "ngaji yinyay | mother's.father there", "r159_deictic_mothers_father_there", ["ngaji", "yinyay"], "Dictionary/Patz ngaji mother's father; bare target."),
    row(6, "The son's child is there.", "Jija yinyay.", "jija yinyay | son's.child there", "r159_deictic_sons_child_there", ["jija", "yinyay"], "Dictionary jija grandchild from son's child; bare target."),
    row(7, "The daughter's child is there.", "Kaminjarr yinyay.", "kaminjarr yinyay | daughter's.child there", "r159_deictic_daughters_child_there", ["kaminjarr", "yinyay"], "Dictionary/Patz kaminjarr grandchild from daughter's child; bare target."),
    row(8, "The son or daughter is there.", "Kangkal yinyay.", "kangkal yinyay | own.child there", "r159_deictic_own_child_there", ["kangkal", "yinyay"], "Dictionary/Patz kangkal own child; no possessive morphology."),
    row(9, "The older brother is there.", "Yaba yinyay.", "yaba yinyay | older.brother there", "r159_deictic_older_brother_there", ["yaba", "yinyay"], "Dictionary/Patz yaba older brother; eel homograph closed."),
    row(10, "The older sister is there.", "Babarr yinyay.", "babarr yinyay | older.sister there", "r159_deictic_older_sister_there", ["babarr", "yinyay"], "Dictionary/Patz babarr older sister; young-cassowary homograph closed."),
    row(11, "I see the grandmother.", "Ngayu babi nyajil.", "ngayu babi nyaji-l | I grandmother see-NONPAST", "r159_present_i_grandmother", ["ngayu", "babi", "nyaji-l"], "Pronoun A bare; grandmother object bare."),
    row(12, "I see the grandfather.", "Ngayu kami nyajil.", "ngayu kami nyaji-l | I grandfather see-NONPAST", "r159_present_i_grandfather", ["ngayu", "kami", "nyaji-l"], "Pronoun A bare; grandfather object bare."),
    row(13, "I see the mother's brother.", "Ngayu kalnga nyajil.", "ngayu kalnga nyaji-l | I mother's.brother see-NONPAST", "r159_present_i_mothers_brother", ["ngayu", "kalnga", "nyaji-l"], "Pronoun A bare; kalnga object bare."),
    row(14, "I see the father's sister.", "Ngayu bimakay nyajil.", "ngayu bimakay nyaji-l | I father's.sister see-NONPAST", "r159_present_i_fathers_sister", ["ngayu", "bimakay", "nyaji-l"], "Pronoun A bare; bimakay object bare."),
    row(15, "I see the mother's father.", "Ngayu ngaji nyajil.", "ngayu ngaji nyaji-l | I mother's.father see-NONPAST", "r159_present_i_mothers_father", ["ngayu", "ngaji", "nyaji-l"], "Pronoun A bare; ngaji object bare."),
    row(16, "I see the son's child.", "Ngayu jija nyajil.", "ngayu jija nyaji-l | I son's.child see-NONPAST", "r159_present_i_sons_child", ["ngayu", "jija", "nyaji-l"], "Pronoun A bare; jija object bare."),
    row(17, "I see the daughter's child.", "Ngayu kaminjarr nyajil.", "ngayu kaminjarr nyaji-l | I daughter's.child see-NONPAST", "r159_present_i_daughters_child", ["ngayu", "kaminjarr", "nyaji-l"], "Pronoun A bare; kaminjarr object bare."),
    row(18, "I see the son or daughter.", "Ngayu kangkal nyajil.", "ngayu kangkal nyaji-l | I own.child see-NONPAST", "r159_present_i_own_child", ["ngayu", "kangkal", "nyaji-l"], "Pronoun A bare; kangkal object bare."),
    row(19, "I see the older brother.", "Ngayu yaba nyajil.", "ngayu yaba nyaji-l | I older.brother see-NONPAST", "r159_present_i_older_brother", ["ngayu", "yaba", "nyaji-l"], "Pronoun A bare; older-brother sense only."),
    row(20, "I see the older sister.", "Ngayu babarr nyajil.", "ngayu babarr nyaji-l | I older.sister see-NONPAST", "r159_present_i_older_sister", ["ngayu", "babarr", "nyaji-l"], "Pronoun A bare; older-sister sense only."),
    row(21, "You see the grandmother.", "Yundu babi nyajil.", "yundu babi nyaji-l | you grandmother see-NONPAST", "r159_present_you_grandmother", ["yundu", "babi", "nyaji-l"], "Second-person pronoun A bare; grandmother object bare."),
    row(22, "You see the grandfather.", "Yundu kami nyajil.", "yundu kami nyaji-l | you grandfather see-NONPAST", "r159_present_you_grandfather", ["yundu", "kami", "nyaji-l"], "Second-person pronoun A bare; grandfather object bare."),
    row(23, "You see the mother's brother.", "Yundu kalnga nyajil.", "yundu kalnga nyaji-l | you mother's.brother see-NONPAST", "r159_present_you_mothers_brother", ["yundu", "kalnga", "nyaji-l"], "Second-person pronoun A bare; kalnga object bare."),
    row(24, "You see the father's sister.", "Yundu bimakay nyajil.", "yundu bimakay nyaji-l | you father's.sister see-NONPAST", "r159_present_you_fathers_sister", ["yundu", "bimakay", "nyaji-l"], "Second-person pronoun A bare; bimakay object bare."),
    row(25, "You see the mother's father.", "Yundu ngaji nyajil.", "yundu ngaji nyaji-l | you mother's.father see-NONPAST", "r159_present_you_mothers_father", ["yundu", "ngaji", "nyaji-l"], "Second-person pronoun A bare; ngaji object bare."),
    row(26, "You see the son's child.", "Yundu jija nyajil.", "yundu jija nyaji-l | you son's.child see-NONPAST", "r159_present_you_sons_child", ["yundu", "jija", "nyaji-l"], "Second-person pronoun A bare; jija object bare."),
    row(27, "You see the daughter's child.", "Yundu kaminjarr nyajil.", "yundu kaminjarr nyaji-l | you daughter's.child see-NONPAST", "r159_present_you_daughters_child", ["yundu", "kaminjarr", "nyaji-l"], "Second-person pronoun A bare; kaminjarr object bare."),
    row(28, "You see the son or daughter.", "Yundu kangkal nyajil.", "yundu kangkal nyaji-l | you own.child see-NONPAST", "r159_present_you_own_child", ["yundu", "kangkal", "nyaji-l"], "Second-person pronoun A bare; own-child sense only."),
    row(29, "You see the older brother.", "Yundu yaba nyajil.", "yundu yaba nyaji-l | you older.brother see-NONPAST", "r159_present_you_older_brother", ["yundu", "yaba", "nyaji-l"], "Second-person pronoun A bare; older-brother sense only."),
    row(30, "You see the older sister.", "Yundu babarr nyajil.", "yundu babarr nyaji-l | you older.sister see-NONPAST", "r159_present_you_older_sister", ["yundu", "babarr", "nyaji-l"], "Second-person pronoun A bare; older-sister sense only."),
    row(31, "They saw the grandmother.", "Jana babi nyajin.", "jana babi nyaji-ny | they grandmother see-PAST", "r159_past_they_grandmother", ["jana", "babi", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the grandfather.", "Jana kami nyajin.", "jana kami nyaji-ny | they grandfather see-PAST", "r159_past_they_grandfather", ["jana", "kami", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(33, "They saw the mother's brother.", "Jana kalnga nyajin.", "jana kalnga nyaji-ny | they mother's.brother see-PAST", "r159_past_they_mothers_brother", ["jana", "kalnga", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(34, "They saw the father's sister.", "Jana bimakay nyajin.", "jana bimakay nyaji-ny | they father's.sister see-PAST", "r159_past_they_fathers_sister", ["jana", "bimakay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(35, "They saw the mother's father.", "Jana ngaji nyajin.", "jana ngaji nyaji-ny | they mother's.father see-PAST", "r159_past_they_mothers_father", ["jana", "ngaji", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(36, "They saw the son's child.", "Jana jija nyajin.", "jana jija nyaji-ny | they son's.child see-PAST", "r159_past_they_sons_child", ["jana", "jija", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(37, "They saw the daughter's child.", "Jana kaminjarr nyajin.", "jana kaminjarr nyaji-ny | they daughter's.child see-PAST", "r159_past_they_daughters_child", ["jana", "kaminjarr", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(38, "They saw the son or daughter.", "Jana kangkal nyajin.", "jana kangkal nyaji-ny | they own.child see-PAST", "r159_past_they_own_child", ["jana", "kangkal", "nyaji-l"], "Third-person plural pronoun A bare; own-child sense only."),
    row(39, "They saw the older brother.", "Jana yaba nyajin.", "jana yaba nyaji-ny | they older.brother see-PAST", "r159_past_they_older_brother", ["jana", "yaba", "nyaji-l"], "Third-person plural pronoun A bare; older-brother sense only."),
    row(40, "They saw the older sister.", "Jana babarr nyajin.", "jana babarr nyaji-ny | they older.sister see-PAST", "r159_past_they_older_sister", ["jana", "babarr", "nyaji-l"], "Third-person plural pronoun A bare; older-sister sense only."),
    row(41, "We see the grandmother here.", "Ngana babi yaluy nyajil.", "ngana babi yaluy nyaji-l | we grandmother here see-NONPAST", "r159_present_we_grandmother_here", ["ngana", "babi", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(42, "We see the grandfather here.", "Ngana kami yaluy nyajil.", "ngana kami yaluy nyaji-l | we grandfather here see-NONPAST", "r159_present_we_grandfather_here", ["ngana", "kami", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(43, "We see the mother's brother here.", "Ngana kalnga yaluy nyajil.", "ngana kalnga yaluy nyaji-l | we mother's.brother here see-NONPAST", "r159_present_we_mothers_brother_here", ["ngana", "kalnga", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(44, "We see the father's sister here.", "Ngana bimakay yaluy nyajil.", "ngana bimakay yaluy nyaji-l | we father's.sister here see-NONPAST", "r159_present_we_fathers_sister_here", ["ngana", "bimakay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(45, "We see the mother's father here.", "Ngana ngaji yaluy nyajil.", "ngana ngaji yaluy nyaji-l | we mother's.father here see-NONPAST", "r159_present_we_mothers_father_here", ["ngana", "ngaji", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(46, "We see the son's child here.", "Ngana jija yaluy nyajil.", "ngana jija yaluy nyaji-l | we son's.child here see-NONPAST", "r159_present_we_sons_child_here", ["ngana", "jija", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(47, "We see the daughter's child here.", "Ngana kaminjarr yaluy nyajil.", "ngana kaminjarr yaluy nyaji-l | we daughter's.child here see-NONPAST", "r159_present_we_daughters_child_here", ["ngana", "kaminjarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(48, "We see the son or daughter here.", "Ngana kangkal yaluy nyajil.", "ngana kangkal yaluy nyaji-l | we own.child here see-NONPAST", "r159_present_we_own_child_here", ["ngana", "kangkal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; own-child sense only."),
    row(49, "We see the older brother here.", "Ngana yaba yaluy nyajil.", "ngana yaba yaluy nyaji-l | we older.brother here see-NONPAST", "r159_present_we_older_brother_here", ["ngana", "yaba", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; older-brother sense only."),
    row(50, "We see the older sister here.", "Ngana babarr yaluy nyajil.", "ngana babarr yaluy nyaji-l | we older.sister here see-NONPAST", "r159_present_we_older_sister_here", ["ngana", "babarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; older-sister sense only."),
]


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)
        is_deictic = seq <= 10
        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("r159_"):
            issues.append(f"{label}: Rule 159 frame must start with r159_")
        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 159")
        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 159 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 is_deictic:
            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:
                issues.append(f"{label}: Rule 159 deictic rows require yinyay")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 159 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 has_token(low, "yaluy") and "yaluy" not in words:
                issues.append(f"{label}: yaluy support missing from words_used")
            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 159 draft: extended-kin reference lexical expansion after Rule 158", "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 159 source pass admitted extended-kin targets babi grandmother, kami grandfather, kalnga mother's "
            "brother, bimakay father's sister, ngaji mother's father, jija son's-child grandchild, kaminjarr "
            "daughter's-child grandchild, kangkal own child, yaba older brother, and babarr older sister. Dictionary, "
            "Patz grammar, lexeme-table, and corpus-surface readback completed."
        ),
        command="dictionary.yaml exact readback; grammar.md kin noun/pronoun/deictic/nyaji readback; sqlite lexeme and surface readback",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="lexical-scope",
        actor="claude-main",
        detail=(
            "Rule 159 is a lexical pass for bare extended-kin reference nouns in deictic and perception frames. It "
            "excludes target case forms, compounds, possessives, kin plurals, address forms, marriage/change-of-state, "
            "avoidance, travel, food, conflict, work, teaching, asking, 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_201.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_201.py static scan", artifact_path="batch_scripts/bank_201.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 159 extended-kin reference lexical-expansion rows.",
                 command="python3 batch_scripts/bank_201.py", artifact_path="batch_scripts/bank_201.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())
