#!/usr/bin/env python3
"""Bank batch-203: Rule 161 literal body-part reference lexical expansion."""

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-203"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-203-literal-body-part-reference-lexical-expansion-after-rule160-process.md"

TARGET_HEADS = {
    "bajibay": "bone",
    "bangkarr": "body",
    "biji": "tail",
    "dirra": "tooth",
    "dukul": "head",
    "manu": "throat",
    "miyil": "eye",
    "ngandal": "mouth",
    "nyabil": "tongue",
    "wakuy": "arm",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "kaka", "bajaburray", "bajibay-kari", "dirra-kari", "miyil-burra", "miyil-dudu", "miyil-kaban",
    "miyil-wurril", "miyil-wujurr", "manu-buray", "dukul-warri", "milka", "jiba", "wawu", "bayka",
    "baykan", "nuka", "nukan", "waju", "wajun", "durrba", "jayba", "daji", "dajin", "yijarri",
    "yijarrin", "julurri", "julurrin", "waka", "kuni", "kunin", "yaka", "yakan", "balka", "balkan",
    "bunda", "bundan", "dunga", "dungan", "kada", "kadan", "wuna", "wunan",
}
DENY_ENGLISH = (
    "sore", "pain", "tired", "sleep", "sleeping", "choke", "choked", "deaf", "blind", "thought",
    "memory", "forget", "emotion", "angry", "sad", "bite", "bit", "eat", "ate", "want", "wanted",
    "give", "gave", "wash", "washed", "put", "cut", "butcher", "meat", "steak", "doctor", "medicine",
    "heal", "healed", "tree", "boss", "boat", "only", "just",
)


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 bone is here.", "Bajibay yaluy.", "bajibay yaluy | bone here", "r161_deictic_bone_here", ["bajibay", "yaluy"], "Rule 161 admits literal bajibay bone in a bare yaluy deictic frame."),
    row(2, "The body is here.", "Bangkarr yaluy.", "bangkarr yaluy | body here", "r161_deictic_body_here", ["bangkarr", "yaluy"], "Rule 161 admits literal bangkarr body, not meat/steak drift."),
    row(3, "The tail is here.", "Biji yaluy.", "biji yaluy | tail here", "r161_deictic_tail_here", ["biji", "yaluy"], "Rule 161 admits literal biji tail with no animal-event frame."),
    row(4, "The tooth is here.", "Dirra yaluy.", "dirra yaluy | tooth here", "r161_deictic_tooth_here", ["dirra", "yaluy"], "Rule 161 admits literal dirra tooth, not dirra-baka or privative."),
    row(5, "The head is here.", "Dukul yaluy.", "dukul yaluy | head here", "r161_deictic_head_here", ["dukul", "yaluy"], "Rule 161 admits literal dukul head; boat/boss/tape senses closed."),
    row(6, "The throat is here.", "Manu yaluy.", "manu yaluy | throat here", "r161_deictic_throat_here", ["manu", "yaluy"], "Rule 161 admits literal manu throat; only/just homograph closed."),
    row(7, "The eye is here.", "Miyil yaluy.", "miyil yaluy | eye here", "r161_deictic_eye_here", ["miyil", "yaluy"], "Rule 161 admits literal miyil eye; poisonous-tree and idiom senses closed."),
    row(8, "The mouth is here.", "Ngandal yaluy.", "ngandal yaluy | mouth here", "r161_deictic_mouth_here", ["ngandal", "yaluy"], "Rule 161 admits literal ngandal mouth."),
    row(9, "The tongue is here.", "Nyabil yaluy.", "nyabil yaluy | tongue here", "r161_deictic_tongue_here", ["nyabil", "yaluy"], "Rule 161 admits literal nyabil tongue."),
    row(10, "The arm is here.", "Wakuy yaluy.", "wakuy yaluy | arm here", "r161_deictic_arm_here", ["wakuy", "yaluy"], "Rule 161 admits literal wakuy arm with y-final locative closed."),
    row(11, "I see the bone there.", "Ngayu bajibay yinyay nyajil.", "ngayu bajibay yinyay nyaji-l | I bone there see-NONPAST", "r161_present_i_bone_there", ["ngayu", "bajibay", "yinyay", "nyaji-l"], "Pronoun A bare; target body-part object bare."),
    row(12, "I see the body there.", "Ngayu bangkarr yinyay nyajil.", "ngayu bangkarr yinyay nyaji-l | I body there see-NONPAST", "r161_present_i_body_there", ["ngayu", "bangkarr", "yinyay", "nyaji-l"], "Pronoun A bare; literal body only."),
    row(13, "I see the tail there.", "Ngayu biji yinyay nyajil.", "ngayu biji yinyay nyaji-l | I tail there see-NONPAST", "r161_present_i_tail_there", ["ngayu", "biji", "yinyay", "nyaji-l"], "Pronoun A bare; no animal-event frame."),
    row(14, "I see the tooth there.", "Ngayu dirra yinyay nyajil.", "ngayu dirra yinyay nyaji-l | I tooth there see-NONPAST", "r161_present_i_tooth_there", ["ngayu", "dirra", "yinyay", "nyaji-l"], "Pronoun A bare; tooth remains literal."),
    row(15, "I see the head there.", "Ngayu dukul yinyay nyajil.", "ngayu dukul yinyay nyaji-l | I head there see-NONPAST", "r161_present_i_head_there", ["ngayu", "dukul", "yinyay", "nyaji-l"], "Pronoun A bare; head sense only."),
    row(16, "I see the throat there.", "Ngayu manu yinyay nyajil.", "ngayu manu yinyay nyaji-l | I throat there see-NONPAST", "r161_present_i_throat_there", ["ngayu", "manu", "yinyay", "nyaji-l"], "Pronoun A bare; throat sense only."),
    row(17, "I see the eye there.", "Ngayu miyil yinyay nyajil.", "ngayu miyil yinyay nyaji-l | I eye there see-NONPAST", "r161_present_i_eye_there", ["ngayu", "miyil", "yinyay", "nyaji-l"], "Pronoun A bare; eye sense only."),
    row(18, "I see the mouth there.", "Ngayu ngandal yinyay nyajil.", "ngayu ngandal yinyay nyaji-l | I mouth there see-NONPAST", "r161_present_i_mouth_there", ["ngayu", "ngandal", "yinyay", "nyaji-l"], "Pronoun A bare; mouth sense only."),
    row(19, "I see the tongue there.", "Ngayu nyabil yinyay nyajil.", "ngayu nyabil yinyay nyaji-l | I tongue there see-NONPAST", "r161_present_i_tongue_there", ["ngayu", "nyabil", "yinyay", "nyaji-l"], "Pronoun A bare; tongue sense only."),
    row(20, "I see the arm there.", "Ngayu wakuy yinyay nyajil.", "ngayu wakuy yinyay nyaji-l | I arm there see-NONPAST", "r161_present_i_arm_there", ["ngayu", "wakuy", "yinyay", "nyaji-l"], "Pronoun A bare; no wakuy case form."),
    row(21, "You see the bone here.", "Yundu bajibay yaluy nyajil.", "yundu bajibay yaluy nyaji-l | you bone here see-NONPAST", "r161_present_you_bone_here", ["yundu", "bajibay", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(22, "You see the body here.", "Yundu bangkarr yaluy nyajil.", "yundu bangkarr yaluy nyaji-l | you body here see-NONPAST", "r161_present_you_body_here", ["yundu", "bangkarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; body sense only."),
    row(23, "You see the tail here.", "Yundu biji yaluy nyajil.", "yundu biji yaluy nyaji-l | you tail here see-NONPAST", "r161_present_you_tail_here", ["yundu", "biji", "yaluy", "nyaji-l"], "Second-person pronoun A bare; tail sense only."),
    row(24, "You see the tooth here.", "Yundu dirra yaluy nyajil.", "yundu dirra yaluy nyaji-l | you tooth here see-NONPAST", "r161_present_you_tooth_here", ["yundu", "dirra", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no privative compound."),
    row(25, "You see the head here.", "Yundu dukul yaluy nyajil.", "yundu dukul yaluy nyaji-l | you head here see-NONPAST", "r161_present_you_head_here", ["yundu", "dukul", "yaluy", "nyaji-l"], "Second-person pronoun A bare; head sense only."),
    row(26, "You see the throat here.", "Yundu manu yaluy nyajil.", "yundu manu yaluy nyaji-l | you throat here see-NONPAST", "r161_present_you_throat_here", ["yundu", "manu", "yaluy", "nyaji-l"], "Second-person pronoun A bare; throat sense only."),
    row(27, "You see the eye here.", "Yundu miyil yaluy nyajil.", "yundu miyil yaluy nyaji-l | you eye here see-NONPAST", "r161_present_you_eye_here", ["yundu", "miyil", "yaluy", "nyaji-l"], "Second-person pronoun A bare; eye sense only."),
    row(28, "You see the mouth here.", "Yundu ngandal yaluy nyajil.", "yundu ngandal yaluy nyaji-l | you mouth here see-NONPAST", "r161_present_you_mouth_here", ["yundu", "ngandal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; mouth sense only."),
    row(29, "You see the tongue here.", "Yundu nyabil yaluy nyajil.", "yundu nyabil yaluy nyaji-l | you tongue here see-NONPAST", "r161_present_you_tongue_here", ["yundu", "nyabil", "yaluy", "nyaji-l"], "Second-person pronoun A bare; tongue sense only."),
    row(30, "You see the arm here.", "Yundu wakuy yaluy nyajil.", "yundu wakuy yaluy nyaji-l | you arm here see-NONPAST", "r161_present_you_arm_here", ["yundu", "wakuy", "yaluy", "nyaji-l"], "Second-person pronoun A bare; arm sense only."),
    row(31, "They saw the bone here.", "Jana bajibay yaluy nyajin.", "jana bajibay yaluy nyaji-ny | they bone here see-PAST", "r161_past_they_bone_here", ["jana", "bajibay", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the body here.", "Jana bangkarr yaluy nyajin.", "jana bangkarr yaluy nyaji-ny | they body here see-PAST", "r161_past_they_body_here", ["jana", "bangkarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; body sense only."),
    row(33, "They saw the tail here.", "Jana biji yaluy nyajin.", "jana biji yaluy nyaji-ny | they tail here see-PAST", "r161_past_they_tail_here", ["jana", "biji", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; tail sense only."),
    row(34, "They saw the tooth here.", "Jana dirra yaluy nyajin.", "jana dirra yaluy nyaji-ny | they tooth here see-PAST", "r161_past_they_tooth_here", ["jana", "dirra", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; tooth sense only."),
    row(35, "They saw the head here.", "Jana dukul yaluy nyajin.", "jana dukul yaluy nyaji-ny | they head here see-PAST", "r161_past_they_head_here", ["jana", "dukul", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; head sense only."),
    row(36, "They saw the throat here.", "Jana manu yaluy nyajin.", "jana manu yaluy nyaji-ny | they throat here see-PAST", "r161_past_they_throat_here", ["jana", "manu", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; throat sense only."),
    row(37, "They saw the eye here.", "Jana miyil yaluy nyajin.", "jana miyil yaluy nyaji-ny | they eye here see-PAST", "r161_past_they_eye_here", ["jana", "miyil", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; eye sense only."),
    row(38, "They saw the mouth here.", "Jana ngandal yaluy nyajin.", "jana ngandal yaluy nyaji-ny | they mouth here see-PAST", "r161_past_they_mouth_here", ["jana", "ngandal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; mouth sense only."),
    row(39, "They saw the tongue here.", "Jana nyabil yaluy nyajin.", "jana nyabil yaluy nyaji-ny | they tongue here see-PAST", "r161_past_they_tongue_here", ["jana", "nyabil", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; tongue sense only."),
    row(40, "They saw the arm here.", "Jana wakuy yaluy nyajin.", "jana wakuy yaluy nyaji-ny | they arm here see-PAST", "r161_past_they_arm_here", ["jana", "wakuy", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; arm sense only."),
    row(41, "We see the bone there.", "Ngana bajibay yinyay nyajil.", "ngana bajibay yinyay nyaji-l | we bone there see-NONPAST", "r161_present_we_bone_there", ["ngana", "bajibay", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support."),
    row(42, "We see the body there.", "Ngana bangkarr yinyay nyajil.", "ngana bangkarr yinyay nyaji-l | we body there see-NONPAST", "r161_present_we_body_there", ["ngana", "bangkarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; body sense only."),
    row(43, "We see the tail there.", "Ngana biji yinyay nyajil.", "ngana biji yinyay nyaji-l | we tail there see-NONPAST", "r161_present_we_tail_there", ["ngana", "biji", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; tail sense only."),
    row(44, "We see the tooth there.", "Ngana dirra yinyay nyajil.", "ngana dirra yinyay nyaji-l | we tooth there see-NONPAST", "r161_present_we_tooth_there", ["ngana", "dirra", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; tooth sense only."),
    row(45, "We see the head there.", "Ngana dukul yinyay nyajil.", "ngana dukul yinyay nyaji-l | we head there see-NONPAST", "r161_present_we_head_there", ["ngana", "dukul", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; head sense only."),
    row(46, "We see the throat there.", "Ngana manu yinyay nyajil.", "ngana manu yinyay nyaji-l | we throat there see-NONPAST", "r161_present_we_throat_there", ["ngana", "manu", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; throat sense only."),
    row(47, "We see the eye there.", "Ngana miyil yinyay nyajil.", "ngana miyil yinyay nyaji-l | we eye there see-NONPAST", "r161_present_we_eye_there", ["ngana", "miyil", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; eye sense only."),
    row(48, "We see the mouth there.", "Ngana ngandal yinyay nyajil.", "ngana ngandal yinyay nyaji-l | we mouth there see-NONPAST", "r161_present_we_mouth_there", ["ngana", "ngandal", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; mouth sense only."),
    row(49, "We see the tongue there.", "Ngana nyabil yinyay nyajil.", "ngana nyabil yinyay nyaji-l | we tongue there see-NONPAST", "r161_present_we_tongue_there", ["ngana", "nyabil", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; tongue sense only."),
    row(50, "We see the arm there.", "Ngana wakuy yinyay nyajil.", "ngana wakuy yinyay nyaji-l | we arm there see-NONPAST", "r161_present_we_arm_there", ["ngana", "wakuy", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; arm 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|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("r161_"):
            issues.append(f"{label}: Rule 161 frame must start with r161_")
        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 161")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied body/event/idiom 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 161 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_HEADS[head] not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {TARGET_HEADS[head]!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if has_token(low, "miyil") and "eye" not in english_low:
            issues.append(f"{label}: miyil must be eye, not tree or idiom")
        if has_token(low, "dukul") and "head" not in english_low:
            issues.append(f"{label}: dukul must be head, not boat/boss/tape")
        if has_token(low, "manu") and "throat" not in english_low:
            issues.append(f"{label}: manu must be throat, not only/just")
        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 161 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 161 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 body/event/homograph 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 161 draft: literal body-part reference lexical expansion after Rule 160", "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 161 source pass selected literal body-part heads bajibay, bangkarr, biji, dirra, dukul, manu, miyil, ngandal, nyabil, and wakuy; 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 body-part/pronoun/deictic/nyaji readback; sqlite lexeme 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 161 is a lexical reference pass for literal body-part heads in bare yaluy deictic and deictic-supported perception frames. It excludes body-state predicates, possession, target case morphology, medical/healing content, eating/butchery content, emotion/cognition idioms, privative compounds, homograph drift, and animal-story events.",
                 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_203.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 literal body-part target per row, selected English senses enforced, no target case or compound morphology, no body-state/event predicates, no homograph drift, yinyay/yaluy support checked, and pronoun A bare.",
                 command="python3 batch_scripts/bank_203.py static scan", artifact_path="batch_scripts/bank_203.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 161 literal body-part reference lexical-expansion rows.",
                 command="python3 batch_scripts/bank_203.py", artifact_path="batch_scripts/bank_203.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())
