#!/usr/bin/env python3
"""Bank batch-204: Rule 162 construction consolidation after Rule 161."""

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-204"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-204-construction-consolidation-after-rule161-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 there.", "Bajibay yinyay.", "bajibay yinyay | bone there", "r162_deictic_bone_there", ["bajibay", "yinyay"], "Rule 162 consolidates literal bajibay bone in a bare yinyay deictic frame."),
    row(2, "The body is there.", "Bangkarr yinyay.", "bangkarr yinyay | body there", "r162_deictic_body_there", ["bangkarr", "yinyay"], "Rule 162 consolidates literal bangkarr body, not meat/steak drift."),
    row(3, "The tail is there.", "Biji yinyay.", "biji yinyay | tail there", "r162_deictic_tail_there", ["biji", "yinyay"], "Rule 162 consolidates literal biji tail with no animal-event frame."),
    row(4, "The tooth is there.", "Dirra yinyay.", "dirra yinyay | tooth there", "r162_deictic_tooth_there", ["dirra", "yinyay"], "Rule 162 consolidates literal dirra tooth, not dirra-baka or privative."),
    row(5, "The head is there.", "Dukul yinyay.", "dukul yinyay | head there", "r162_deictic_head_there", ["dukul", "yinyay"], "Rule 162 consolidates literal dukul head; boat/boss/tape senses closed."),
    row(6, "The throat is there.", "Manu yinyay.", "manu yinyay | throat there", "r162_deictic_throat_there", ["manu", "yinyay"], "Rule 162 consolidates literal manu throat; only/just homograph closed."),
    row(7, "The eye is there.", "Miyil yinyay.", "miyil yinyay | eye there", "r162_deictic_eye_there", ["miyil", "yinyay"], "Rule 162 consolidates literal miyil eye; poisonous-tree and idiom senses closed."),
    row(8, "The mouth is there.", "Ngandal yinyay.", "ngandal yinyay | mouth there", "r162_deictic_mouth_there", ["ngandal", "yinyay"], "Rule 162 consolidates literal ngandal mouth."),
    row(9, "The tongue is there.", "Nyabil yinyay.", "nyabil yinyay | tongue there", "r162_deictic_tongue_there", ["nyabil", "yinyay"], "Rule 162 consolidates literal nyabil tongue."),
    row(10, "The arm is there.", "Wakuy yinyay.", "wakuy yinyay | arm there", "r162_deictic_arm_there", ["wakuy", "yinyay"], "Rule 162 consolidates literal wakuy arm with y-final locative closed."),
    row(11, "I see the bone here.", "Ngayu bajibay yaluy nyajil.", "ngayu bajibay yaluy nyaji-l | I bone here see-NONPAST", "r162_present_i_bone_here", ["ngayu", "bajibay", "yaluy", "nyaji-l"], "Pronoun A bare; target body-part object bare."),
    row(12, "I see the body here.", "Ngayu bangkarr yaluy nyajil.", "ngayu bangkarr yaluy nyaji-l | I body here see-NONPAST", "r162_present_i_body_here", ["ngayu", "bangkarr", "yaluy", "nyaji-l"], "Pronoun A bare; literal body only."),
    row(13, "I see the tail here.", "Ngayu biji yaluy nyajil.", "ngayu biji yaluy nyaji-l | I tail here see-NONPAST", "r162_present_i_tail_here", ["ngayu", "biji", "yaluy", "nyaji-l"], "Pronoun A bare; no animal-event frame."),
    row(14, "I see the tooth here.", "Ngayu dirra yaluy nyajil.", "ngayu dirra yaluy nyaji-l | I tooth here see-NONPAST", "r162_present_i_tooth_here", ["ngayu", "dirra", "yaluy", "nyaji-l"], "Pronoun A bare; tooth remains literal."),
    row(15, "I see the head here.", "Ngayu dukul yaluy nyajil.", "ngayu dukul yaluy nyaji-l | I head here see-NONPAST", "r162_present_i_head_here", ["ngayu", "dukul", "yaluy", "nyaji-l"], "Pronoun A bare; head sense only."),
    row(16, "I see the throat here.", "Ngayu manu yaluy nyajil.", "ngayu manu yaluy nyaji-l | I throat here see-NONPAST", "r162_present_i_throat_here", ["ngayu", "manu", "yaluy", "nyaji-l"], "Pronoun A bare; throat sense only."),
    row(17, "I see the eye here.", "Ngayu miyil yaluy nyajil.", "ngayu miyil yaluy nyaji-l | I eye here see-NONPAST", "r162_present_i_eye_here", ["ngayu", "miyil", "yaluy", "nyaji-l"], "Pronoun A bare; eye sense only."),
    row(18, "I see the mouth here.", "Ngayu ngandal yaluy nyajil.", "ngayu ngandal yaluy nyaji-l | I mouth here see-NONPAST", "r162_present_i_mouth_here", ["ngayu", "ngandal", "yaluy", "nyaji-l"], "Pronoun A bare; mouth sense only."),
    row(19, "I see the tongue here.", "Ngayu nyabil yaluy nyajil.", "ngayu nyabil yaluy nyaji-l | I tongue here see-NONPAST", "r162_present_i_tongue_here", ["ngayu", "nyabil", "yaluy", "nyaji-l"], "Pronoun A bare; tongue sense only."),
    row(20, "I see the arm here.", "Ngayu wakuy yaluy nyajil.", "ngayu wakuy yaluy nyaji-l | I arm here see-NONPAST", "r162_present_i_arm_here", ["ngayu", "wakuy", "yaluy", "nyaji-l"], "Pronoun A bare; no wakuy case form."),
    row(21, "You see the bone there.", "Yundu bajibay yinyay nyajil.", "yundu bajibay yinyay nyaji-l | you bone there see-NONPAST", "r162_present_you_bone_there", ["yundu", "bajibay", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(22, "You see the body there.", "Yundu bangkarr yinyay nyajil.", "yundu bangkarr yinyay nyaji-l | you body there see-NONPAST", "r162_present_you_body_there", ["yundu", "bangkarr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; body sense only."),
    row(23, "You see the tail there.", "Yundu biji yinyay nyajil.", "yundu biji yinyay nyaji-l | you tail there see-NONPAST", "r162_present_you_tail_there", ["yundu", "biji", "yinyay", "nyaji-l"], "Second-person pronoun A bare; tail sense only."),
    row(24, "You see the tooth there.", "Yundu dirra yinyay nyajil.", "yundu dirra yinyay nyaji-l | you tooth there see-NONPAST", "r162_present_you_tooth_there", ["yundu", "dirra", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no privative compound."),
    row(25, "You see the head there.", "Yundu dukul yinyay nyajil.", "yundu dukul yinyay nyaji-l | you head there see-NONPAST", "r162_present_you_head_there", ["yundu", "dukul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; head sense only."),
    row(26, "You see the throat there.", "Yundu manu yinyay nyajil.", "yundu manu yinyay nyaji-l | you throat there see-NONPAST", "r162_present_you_throat_there", ["yundu", "manu", "yinyay", "nyaji-l"], "Second-person pronoun A bare; throat sense only."),
    row(27, "You see the eye there.", "Yundu miyil yinyay nyajil.", "yundu miyil yinyay nyaji-l | you eye there see-NONPAST", "r162_present_you_eye_there", ["yundu", "miyil", "yinyay", "nyaji-l"], "Second-person pronoun A bare; eye sense only."),
    row(28, "You see the mouth there.", "Yundu ngandal yinyay nyajil.", "yundu ngandal yinyay nyaji-l | you mouth there see-NONPAST", "r162_present_you_mouth_there", ["yundu", "ngandal", "yinyay", "nyaji-l"], "Second-person pronoun A bare; mouth sense only."),
    row(29, "You see the tongue there.", "Yundu nyabil yinyay nyajil.", "yundu nyabil yinyay nyaji-l | you tongue there see-NONPAST", "r162_present_you_tongue_there", ["yundu", "nyabil", "yinyay", "nyaji-l"], "Second-person pronoun A bare; tongue sense only."),
    row(30, "You see the arm there.", "Yundu wakuy yinyay nyajil.", "yundu wakuy yinyay nyaji-l | you arm there see-NONPAST", "r162_present_you_arm_there", ["yundu", "wakuy", "yinyay", "nyaji-l"], "Second-person pronoun A bare; arm sense only."),
    row(31, "They saw the bone there.", "Jana bajibay yinyay nyajin.", "jana bajibay yinyay nyaji-ny | they bone there see-PAST", "r162_past_they_bone_there", ["jana", "bajibay", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the body there.", "Jana bangkarr yinyay nyajin.", "jana bangkarr yinyay nyaji-ny | they body there see-PAST", "r162_past_they_body_there", ["jana", "bangkarr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; body sense only."),
    row(33, "They saw the tail there.", "Jana biji yinyay nyajin.", "jana biji yinyay nyaji-ny | they tail there see-PAST", "r162_past_they_tail_there", ["jana", "biji", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; tail sense only."),
    row(34, "They saw the tooth there.", "Jana dirra yinyay nyajin.", "jana dirra yinyay nyaji-ny | they tooth there see-PAST", "r162_past_they_tooth_there", ["jana", "dirra", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; tooth sense only."),
    row(35, "They saw the head there.", "Jana dukul yinyay nyajin.", "jana dukul yinyay nyaji-ny | they head there see-PAST", "r162_past_they_head_there", ["jana", "dukul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; head sense only."),
    row(36, "They saw the throat there.", "Jana manu yinyay nyajin.", "jana manu yinyay nyaji-ny | they throat there see-PAST", "r162_past_they_throat_there", ["jana", "manu", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; throat sense only."),
    row(37, "They saw the eye there.", "Jana miyil yinyay nyajin.", "jana miyil yinyay nyaji-ny | they eye there see-PAST", "r162_past_they_eye_there", ["jana", "miyil", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; eye sense only."),
    row(38, "They saw the mouth there.", "Jana ngandal yinyay nyajin.", "jana ngandal yinyay nyaji-ny | they mouth there see-PAST", "r162_past_they_mouth_there", ["jana", "ngandal", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; mouth sense only."),
    row(39, "They saw the tongue there.", "Jana nyabil yinyay nyajin.", "jana nyabil yinyay nyaji-ny | they tongue there see-PAST", "r162_past_they_tongue_there", ["jana", "nyabil", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; tongue sense only."),
    row(40, "They saw the arm there.", "Jana wakuy yinyay nyajin.", "jana wakuy yinyay nyaji-ny | they arm there see-PAST", "r162_past_they_arm_there", ["jana", "wakuy", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; arm sense only."),
    row(41, "We see the bone here.", "Ngana bajibay yaluy nyajil.", "ngana bajibay yaluy nyaji-l | we bone here see-NONPAST", "r162_present_we_bone_here", ["ngana", "bajibay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(42, "We see the body here.", "Ngana bangkarr yaluy nyajil.", "ngana bangkarr yaluy nyaji-l | we body here see-NONPAST", "r162_present_we_body_here", ["ngana", "bangkarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; body sense only."),
    row(43, "We see the tail here.", "Ngana biji yaluy nyajil.", "ngana biji yaluy nyaji-l | we tail here see-NONPAST", "r162_present_we_tail_here", ["ngana", "biji", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; tail sense only."),
    row(44, "We see the tooth here.", "Ngana dirra yaluy nyajil.", "ngana dirra yaluy nyaji-l | we tooth here see-NONPAST", "r162_present_we_tooth_here", ["ngana", "dirra", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; tooth sense only."),
    row(45, "We see the head here.", "Ngana dukul yaluy nyajil.", "ngana dukul yaluy nyaji-l | we head here see-NONPAST", "r162_present_we_head_here", ["ngana", "dukul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; head sense only."),
    row(46, "We see the throat here.", "Ngana manu yaluy nyajil.", "ngana manu yaluy nyaji-l | we throat here see-NONPAST", "r162_present_we_throat_here", ["ngana", "manu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; throat sense only."),
    row(47, "We see the eye here.", "Ngana miyil yaluy nyajil.", "ngana miyil yaluy nyaji-l | we eye here see-NONPAST", "r162_present_we_eye_here", ["ngana", "miyil", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; eye sense only."),
    row(48, "We see the mouth here.", "Ngana ngandal yaluy nyajil.", "ngana ngandal yaluy nyaji-l | we mouth here see-NONPAST", "r162_present_we_mouth_here", ["ngana", "ngandal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; mouth sense only."),
    row(49, "We see the tongue here.", "Ngana nyabil yaluy nyajil.", "ngana nyabil yaluy nyaji-l | we tongue here see-NONPAST", "r162_present_we_tongue_here", ["ngana", "nyabil", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; tongue sense only."),
    row(50, "We see the arm here.", "Ngana wakuy yaluy nyajil.", "ngana wakuy yaluy nyaji-l | we arm here see-NONPAST", "r162_present_we_arm_here", ["ngana", "wakuy", "yaluy", "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("r162_"):
            issues.append(f"{label}: Rule 162 frame must start with r162_")
        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 162")
        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 162 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, "yinyay") or "yinyay" not in words or "there" not in english_low:
                issues.append(f"{label}: Rule 162 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 162 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, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            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 162 draft: construction consolidation after Rule 161", "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 162 source pass retained 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="construction-scope", actor="claude-main",
                 detail="Rule 162 is a construction consolidation pass for the Rule 161 literal body-part set. It swaps deictic support distribution while excluding 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_204.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_204.py static scan", artifact_path="batch_scripts/bank_204.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 162 literal body-part construction-consolidation rows.",
                 command="python3 batch_scripts/bank_204.py", artifact_path="batch_scripts/bank_204.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())
