#!/usr/bin/env python3
"""Bank batch-199: Rule 157 human/kin reference lexical expansion after Rule 156."""

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

TARGET_HEADS = {
    "bama": "person",
    "dingkar": "man",
    "jalbu": "woman",
    "karrkay": "child",
    "ngamu": "mother",
    "nganjan": "father",
    "jawun": "friend",
    "dunyu": "husband",
    "warru": "young.man",
    "wulman": "old.man",
}
TARGET_ENGLISH = {
    "bama": "person",
    "dingkar": "man",
    "jalbu": "woman",
    "karrkay": "child",
    "ngamu": "mother",
    "nganjan": "father",
    "jawun": "friend",
    "dunyu": "husband",
    "warru": "young man",
    "wulman": "old man",
}
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", "jawun-karra", "dunyu-karra", "warru-warru", "jalbu-jalbu",
}
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", "husband became", "wife", "relative", "relations", "with a friend", "many", "crowd", "old animal",
)


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 person is there.", "Bama yinyay.", "bama yinyay | person there", "r157_deictic_person_there", ["bama", "yinyay"], "Dictionary bama people/person; Patz generic human term and 'that person' example."),
    row(2, "The man is there.", "Dingkar yinyay.", "dingkar yinyay | man there", "r157_deictic_man_there", ["dingkar", "yinyay"], "Dictionary/Patz dingkar male/man; bare deictic only."),
    row(3, "The woman is there.", "Jalbu yinyay.", "jalbu yinyay | woman there", "r157_deictic_woman_there", ["jalbu", "yinyay"], "Dictionary/Patz jalbu female/woman; bare deictic only."),
    row(4, "The child is there.", "Karrkay yinyay.", "karrkay yinyay | child there", "r157_deictic_child_there", ["karrkay", "yinyay"], "Dictionary karrkay child/young one; noun sense only."),
    row(5, "The mother is there.", "Ngamu yinyay.", "ngamu yinyay | mother there", "r157_deictic_mother_there", ["ngamu", "yinyay"], "Dictionary/Patz ngamu mother; kin noun only."),
    row(6, "The father is there.", "Nganjan yinyay.", "nganjan yinyay | father there", "r157_deictic_father_there", ["nganjan", "yinyay"], "Dictionary/Patz nganjan father; kin noun only."),
    row(7, "The friend is there.", "Jawun yinyay.", "jawun yinyay | friend there", "r157_deictic_friend_there", ["jawun", "yinyay"], "Dictionary/Patz jawun friend/relation; selected friend sense."),
    row(8, "The husband is there.", "Dunyu yinyay.", "dunyu yinyay | husband there", "r157_deictic_husband_there", ["dunyu", "yinyay"], "Dictionary/Patz dunyu husband; bare deictic only."),
    row(9, "The young man is there.", "Warru yinyay.", "warru yinyay | young.man there", "r157_deictic_young_man_there", ["warru", "yinyay"], "Dictionary/Patz warru young man; no plural/pair row."),
    row(10, "The old man is there.", "Wulman yinyay.", "wulman yinyay | old.man there", "r157_deictic_old_man_there", ["wulman", "yinyay"], "Dictionary/Patz wulman old man; no husband/old-animal sense."),
    row(11, "I see the person.", "Ngayu bama nyajil.", "ngayu bama nyaji-l | I person see-NONPAST", "r157_present_i_person", ["ngayu", "bama", "nyaji-l"], "Pronoun A bare; bama selected person sense."),
    row(12, "I see the man.", "Ngayu dingkar nyajil.", "ngayu dingkar nyaji-l | I man see-NONPAST", "r157_present_i_man", ["ngayu", "dingkar", "nyaji-l"], "Pronoun A bare; dingkar object bare."),
    row(13, "I see the woman.", "Ngayu jalbu nyajil.", "ngayu jalbu nyaji-l | I woman see-NONPAST", "r157_present_i_woman", ["ngayu", "jalbu", "nyaji-l"], "Pronoun A bare; jalbu object bare."),
    row(14, "I see the child.", "Ngayu karrkay nyajil.", "ngayu karrkay nyaji-l | I child see-NONPAST", "r157_present_i_child", ["ngayu", "karrkay", "nyaji-l"], "Pronoun A bare; karrkay noun sense."),
    row(15, "I see the mother.", "Ngayu ngamu nyajil.", "ngayu ngamu nyaji-l | I mother see-NONPAST", "r157_present_i_mother", ["ngayu", "ngamu", "nyaji-l"], "Pronoun A bare; ngamu object bare."),
    row(16, "I see the father.", "Ngayu nganjan nyajil.", "ngayu nganjan nyaji-l | I father see-NONPAST", "r157_present_i_father", ["ngayu", "nganjan", "nyaji-l"], "Pronoun A bare; nganjan object bare."),
    row(17, "I see the friend.", "Ngayu jawun nyajil.", "ngayu jawun nyaji-l | I friend see-NONPAST", "r157_present_i_friend", ["ngayu", "jawun", "nyaji-l"], "Pronoun A bare; jawun selected friend sense."),
    row(18, "I see the husband.", "Ngayu dunyu nyajil.", "ngayu dunyu nyaji-l | I husband see-NONPAST", "r157_present_i_husband", ["ngayu", "dunyu", "nyaji-l"], "Pronoun A bare; dunyu object bare."),
    row(19, "I see the young man.", "Ngayu warru nyajil.", "ngayu warru nyaji-l | I young.man see-NONPAST", "r157_present_i_young_man", ["ngayu", "warru", "nyaji-l"], "Pronoun A bare; warru object bare."),
    row(20, "I see the old man.", "Ngayu wulman nyajil.", "ngayu wulman nyaji-l | I old.man see-NONPAST", "r157_present_i_old_man", ["ngayu", "wulman", "nyaji-l"], "Pronoun A bare; wulman old-man sense."),
    row(21, "You see the person.", "Yundu bama nyajil.", "yundu bama nyaji-l | you person see-NONPAST", "r157_present_you_person", ["yundu", "bama", "nyaji-l"], "Second-person pronoun A bare; bama selected person sense."),
    row(22, "You see the man.", "Yundu dingkar nyajil.", "yundu dingkar nyaji-l | you man see-NONPAST", "r157_present_you_man", ["yundu", "dingkar", "nyaji-l"], "Second-person pronoun A bare; dingkar object bare."),
    row(23, "You see the woman.", "Yundu jalbu nyajil.", "yundu jalbu nyaji-l | you woman see-NONPAST", "r157_present_you_woman", ["yundu", "jalbu", "nyaji-l"], "Second-person pronoun A bare; jalbu object bare."),
    row(24, "You see the child.", "Yundu karrkay nyajil.", "yundu karrkay nyaji-l | you child see-NONPAST", "r157_present_you_child", ["yundu", "karrkay", "nyaji-l"], "Second-person pronoun A bare; child noun only."),
    row(25, "You see the mother.", "Yundu ngamu nyajil.", "yundu ngamu nyaji-l | you mother see-NONPAST", "r157_present_you_mother", ["yundu", "ngamu", "nyaji-l"], "Second-person pronoun A bare; kin noun object."),
    row(26, "You see the father.", "Yundu nganjan nyajil.", "yundu nganjan nyaji-l | you father see-NONPAST", "r157_present_you_father", ["yundu", "nganjan", "nyaji-l"], "Second-person pronoun A bare; kin noun object."),
    row(27, "You see the friend.", "Yundu jawun nyajil.", "yundu jawun nyaji-l | you friend see-NONPAST", "r157_present_you_friend", ["yundu", "jawun", "nyaji-l"], "Second-person pronoun A bare; friend sense only."),
    row(28, "You see the husband.", "Yundu dunyu nyajil.", "yundu dunyu nyaji-l | you husband see-NONPAST", "r157_present_you_husband", ["yundu", "dunyu", "nyaji-l"], "Second-person pronoun A bare; husband noun only."),
    row(29, "You see the young man.", "Yundu warru nyajil.", "yundu warru nyaji-l | you young.man see-NONPAST", "r157_present_you_young_man", ["yundu", "warru", "nyaji-l"], "Second-person pronoun A bare; young-man noun only."),
    row(30, "You see the old man.", "Yundu wulman nyajil.", "yundu wulman nyaji-l | you old.man see-NONPAST", "r157_present_you_old_man", ["yundu", "wulman", "nyaji-l"], "Second-person pronoun A bare; old-man sense only."),
    row(31, "They saw the person.", "Jana bama nyajin.", "jana bama nyaji-ny | they person see-PAST", "r157_past_they_person", ["jana", "bama", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the man.", "Jana dingkar nyajin.", "jana dingkar nyaji-ny | they man see-PAST", "r157_past_they_man", ["jana", "dingkar", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(33, "They saw the woman.", "Jana jalbu nyajin.", "jana jalbu nyaji-ny | they woman see-PAST", "r157_past_they_woman", ["jana", "jalbu", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(34, "They saw the child.", "Jana karrkay nyajin.", "jana karrkay nyaji-ny | they child see-PAST", "r157_past_they_child", ["jana", "karrkay", "nyaji-l"], "Third-person plural pronoun A bare; child noun object."),
    row(35, "They saw the mother.", "Jana ngamu nyajin.", "jana ngamu nyaji-ny | they mother see-PAST", "r157_past_they_mother", ["jana", "ngamu", "nyaji-l"], "Third-person plural pronoun A bare; kin noun object."),
    row(36, "They saw the father.", "Jana nganjan nyajin.", "jana nganjan nyaji-ny | they father see-PAST", "r157_past_they_father", ["jana", "nganjan", "nyaji-l"], "Third-person plural pronoun A bare; kin noun object."),
    row(37, "They saw the friend.", "Jana jawun nyajin.", "jana jawun nyaji-ny | they friend see-PAST", "r157_past_they_friend", ["jana", "jawun", "nyaji-l"], "Third-person plural pronoun A bare; friend sense only."),
    row(38, "They saw the husband.", "Jana dunyu nyajin.", "jana dunyu nyaji-ny | they husband see-PAST", "r157_past_they_husband", ["jana", "dunyu", "nyaji-l"], "Third-person plural pronoun A bare; husband noun only."),
    row(39, "They saw the young man.", "Jana warru nyajin.", "jana warru nyaji-ny | they young.man see-PAST", "r157_past_they_young_man", ["jana", "warru", "nyaji-l"], "Third-person plural pronoun A bare; young-man noun only."),
    row(40, "They saw the old man.", "Jana wulman nyajin.", "jana wulman nyaji-ny | they old.man see-PAST", "r157_past_they_old_man", ["jana", "wulman", "nyaji-l"], "Third-person plural pronoun A bare; old-man sense only."),
    row(41, "We see the person here.", "Ngana bama yaluy nyajil.", "ngana bama yaluy nyaji-l | we person here see-NONPAST", "r157_present_we_person_here", ["ngana", "bama", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(42, "We see the man here.", "Ngana dingkar yaluy nyajil.", "ngana dingkar yaluy nyaji-l | we man here see-NONPAST", "r157_present_we_man_here", ["ngana", "dingkar", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(43, "We see the woman here.", "Ngana jalbu yaluy nyajil.", "ngana jalbu yaluy nyaji-l | we woman here see-NONPAST", "r157_present_we_woman_here", ["ngana", "jalbu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support."),
    row(44, "We see the child here.", "Ngana karrkay yaluy nyajil.", "ngana karrkay yaluy nyaji-l | we child here see-NONPAST", "r157_present_we_child_here", ["ngana", "karrkay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; child noun only."),
    row(45, "We see the mother here.", "Ngana ngamu yaluy nyajil.", "ngana ngamu yaluy nyaji-l | we mother here see-NONPAST", "r157_present_we_mother_here", ["ngana", "ngamu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; mother noun only."),
    row(46, "We see the father here.", "Ngana nganjan yaluy nyajil.", "ngana nganjan yaluy nyaji-l | we father here see-NONPAST", "r157_present_we_father_here", ["ngana", "nganjan", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; father noun only."),
    row(47, "We see the friend here.", "Ngana jawun yaluy nyajil.", "ngana jawun yaluy nyaji-l | we friend here see-NONPAST", "r157_present_we_friend_here", ["ngana", "jawun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; friend sense only."),
    row(48, "We see the husband here.", "Ngana dunyu yaluy nyajil.", "ngana dunyu yaluy nyaji-l | we husband here see-NONPAST", "r157_present_we_husband_here", ["ngana", "dunyu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; husband noun only."),
    row(49, "We see the young man here.", "Ngana warru yaluy nyajil.", "ngana warru yaluy nyaji-l | we young.man here see-NONPAST", "r157_present_we_young_man_here", ["ngana", "warru", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; young-man noun only."),
    row(50, "We see the old man here.", "Ngana wulman yaluy nyajil.", "ngana wulman yaluy nyaji-l | we old.man here see-NONPAST", "r157_present_we_old_man_here", ["ngana", "wulman", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; old-man 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)\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("r157_"):
            issues.append(f"{label}: Rule 157 frame must start with r157_")
        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 157")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied human/kin event 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 157 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, "karrkay") and "child" not in english_low:
            issues.append(f"{label}: karrkay must be translated as child, not adjective small")
        if has_token(low, "jawun") and "friend" not in english_low:
            issues.append(f"{label}: jawun must be translated with selected friend sense")
        if has_token(low, "wulman") and "old man" not in english_low:
            issues.append(f"{label}: wulman must be translated as old man in Rule 157")
        if has_token(low, "warru") and "young man" not in english_low:
            issues.append(f"{label}: warru must be translated as young man in Rule 157")
        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 157 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 157 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 human/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 157 draft: human/kin reference lexical expansion after Rule 156", "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 157 source pass admitted human/kin reference targets bama person, dingkar man, jalbu woman, "
            "karrkay child, ngamu mother, nganjan father, jawun friend, dunyu husband, warru young man, and wulman "
            "old man. Dictionary, Patz grammar, lexeme-table, and corpus-surface readback completed; bama was sourced "
            "from dictionary/Patz and marked for lexeme-table insertion at close."
        ),
        command="dictionary.yaml exact readback; grammar.md 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 157 is a lexical pass for bare human/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_199.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 human/kin target per row, selected English senses enforced, no target case or compound morphology, no kin/social-event predicates, no action import, yinyay/yaluy support checked, and pronoun A bare.",
                 command="python3 batch_scripts/bank_199.py static scan", artifact_path="batch_scripts/bank_199.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 157 human/kin reference lexical-expansion rows.",
                 command="python3 batch_scripts/bank_199.py", artifact_path="batch_scripts/bank_199.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())
