#!/usr/bin/env python3
"""Bank batch-200: Rule 158 construction consolidation after Rule 157."""

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-200"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-200-construction-consolidation-after-rule157-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 here.", "Bama yaluy.", "bama yaluy | person here", "r158_deictic_person_here", ["bama", "yaluy"], "Rule 158 consolidates bama in a bare yaluy deictic frame."),
    row(2, "The man is here.", "Dingkar yaluy.", "dingkar yaluy | man here", "r158_deictic_man_here", ["dingkar", "yaluy"], "Bare target plus yaluy; no event semantics."),
    row(3, "The woman is here.", "Jalbu yaluy.", "jalbu yaluy | woman here", "r158_deictic_woman_here", ["jalbu", "yaluy"], "Bare target plus yaluy; woman noun only."),
    row(4, "The child is here.", "Karrkay yaluy.", "karrkay yaluy | child here", "r158_deictic_child_here", ["karrkay", "yaluy"], "Karrkay remains child noun only."),
    row(5, "The mother is here.", "Ngamu yaluy.", "ngamu yaluy | mother here", "r158_deictic_mother_here", ["ngamu", "yaluy"], "Ngamu remains mother noun only."),
    row(6, "The father is here.", "Nganjan yaluy.", "nganjan yaluy | father here", "r158_deictic_father_here", ["nganjan", "yaluy"], "Nganjan remains father noun only."),
    row(7, "The friend is here.", "Jawun yaluy.", "jawun yaluy | friend here", "r158_deictic_friend_here", ["jawun", "yaluy"], "Jawun remains selected friend sense."),
    row(8, "The husband is here.", "Dunyu yaluy.", "dunyu yaluy | husband here", "r158_deictic_husband_here", ["dunyu", "yaluy"], "Dunyu remains husband noun only."),
    row(9, "The young man is here.", "Warru yaluy.", "warru yaluy | young.man here", "r158_deictic_young_man_here", ["warru", "yaluy"], "Warru remains young-man noun only."),
    row(10, "The old man is here.", "Wulman yaluy.", "wulman yaluy | old.man here", "r158_deictic_old_man_here", ["wulman", "yaluy"], "Wulman remains old-man sense only."),
    row(11, "I see the person there.", "Ngayu bama yinyay nyajil.", "ngayu bama yinyay nyaji-l | I person there see-NONPAST", "r158_present_i_person_there", ["ngayu", "bama", "yinyay", "nyaji-l"], "Pronoun A bare; yinyay support only."),
    row(12, "I see the man there.", "Ngayu dingkar yinyay nyajil.", "ngayu dingkar yinyay nyaji-l | I man there see-NONPAST", "r158_present_i_man_there", ["ngayu", "dingkar", "yinyay", "nyaji-l"], "Pronoun A bare; dingkar object bare."),
    row(13, "I see the woman there.", "Ngayu jalbu yinyay nyajil.", "ngayu jalbu yinyay nyaji-l | I woman there see-NONPAST", "r158_present_i_woman_there", ["ngayu", "jalbu", "yinyay", "nyaji-l"], "Pronoun A bare; jalbu object bare."),
    row(14, "I see the child there.", "Ngayu karrkay yinyay nyajil.", "ngayu karrkay yinyay nyaji-l | I child there see-NONPAST", "r158_present_i_child_there", ["ngayu", "karrkay", "yinyay", "nyaji-l"], "Pronoun A bare; child noun only."),
    row(15, "I see the mother there.", "Ngayu ngamu yinyay nyajil.", "ngayu ngamu yinyay nyaji-l | I mother there see-NONPAST", "r158_present_i_mother_there", ["ngayu", "ngamu", "yinyay", "nyaji-l"], "Pronoun A bare; mother noun only."),
    row(16, "I see the father there.", "Ngayu nganjan yinyay nyajil.", "ngayu nganjan yinyay nyaji-l | I father there see-NONPAST", "r158_present_i_father_there", ["ngayu", "nganjan", "yinyay", "nyaji-l"], "Pronoun A bare; father noun only."),
    row(17, "I see the friend there.", "Ngayu jawun yinyay nyajil.", "ngayu jawun yinyay nyaji-l | I friend there see-NONPAST", "r158_present_i_friend_there", ["ngayu", "jawun", "yinyay", "nyaji-l"], "Pronoun A bare; friend sense only."),
    row(18, "I see the husband there.", "Ngayu dunyu yinyay nyajil.", "ngayu dunyu yinyay nyaji-l | I husband there see-NONPAST", "r158_present_i_husband_there", ["ngayu", "dunyu", "yinyay", "nyaji-l"], "Pronoun A bare; husband noun only."),
    row(19, "I see the young man there.", "Ngayu warru yinyay nyajil.", "ngayu warru yinyay nyaji-l | I young.man there see-NONPAST", "r158_present_i_young_man_there", ["ngayu", "warru", "yinyay", "nyaji-l"], "Pronoun A bare; young-man noun only."),
    row(20, "I see the old man there.", "Ngayu wulman yinyay nyajil.", "ngayu wulman yinyay nyaji-l | I old.man there see-NONPAST", "r158_present_i_old_man_there", ["ngayu", "wulman", "yinyay", "nyaji-l"], "Pronoun A bare; old-man sense only."),
    row(21, "You see the person here.", "Yundu bama yaluy nyajil.", "yundu bama yaluy nyaji-l | you person here see-NONPAST", "r158_present_you_person_here", ["yundu", "bama", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support."),
    row(22, "You see the man here.", "Yundu dingkar yaluy nyajil.", "yundu dingkar yaluy nyaji-l | you man here see-NONPAST", "r158_present_you_man_here", ["yundu", "dingkar", "yaluy", "nyaji-l"], "Second-person pronoun A bare; dingkar object bare."),
    row(23, "You see the woman here.", "Yundu jalbu yaluy nyajil.", "yundu jalbu yaluy nyaji-l | you woman here see-NONPAST", "r158_present_you_woman_here", ["yundu", "jalbu", "yaluy", "nyaji-l"], "Second-person pronoun A bare; jalbu object bare."),
    row(24, "You see the child here.", "Yundu karrkay yaluy nyajil.", "yundu karrkay yaluy nyaji-l | you child here see-NONPAST", "r158_present_you_child_here", ["yundu", "karrkay", "yaluy", "nyaji-l"], "Second-person pronoun A bare; child noun only."),
    row(25, "You see the mother here.", "Yundu ngamu yaluy nyajil.", "yundu ngamu yaluy nyaji-l | you mother here see-NONPAST", "r158_present_you_mother_here", ["yundu", "ngamu", "yaluy", "nyaji-l"], "Second-person pronoun A bare; mother noun only."),
    row(26, "You see the father here.", "Yundu nganjan yaluy nyajil.", "yundu nganjan yaluy nyaji-l | you father here see-NONPAST", "r158_present_you_father_here", ["yundu", "nganjan", "yaluy", "nyaji-l"], "Second-person pronoun A bare; father noun only."),
    row(27, "You see the friend here.", "Yundu jawun yaluy nyajil.", "yundu jawun yaluy nyaji-l | you friend here see-NONPAST", "r158_present_you_friend_here", ["yundu", "jawun", "yaluy", "nyaji-l"], "Second-person pronoun A bare; friend sense only."),
    row(28, "You see the husband here.", "Yundu dunyu yaluy nyajil.", "yundu dunyu yaluy nyaji-l | you husband here see-NONPAST", "r158_present_you_husband_here", ["yundu", "dunyu", "yaluy", "nyaji-l"], "Second-person pronoun A bare; husband noun only."),
    row(29, "You see the young man here.", "Yundu warru yaluy nyajil.", "yundu warru yaluy nyaji-l | you young.man here see-NONPAST", "r158_present_you_young_man_here", ["yundu", "warru", "yaluy", "nyaji-l"], "Second-person pronoun A bare; young-man noun only."),
    row(30, "You see the old man here.", "Yundu wulman yaluy nyajil.", "yundu wulman yaluy nyaji-l | you old.man here see-NONPAST", "r158_present_you_old_man_here", ["yundu", "wulman", "yaluy", "nyaji-l"], "Second-person pronoun A bare; old-man sense only."),
    row(31, "They saw the person here.", "Jana bama yaluy nyajin.", "jana bama yaluy nyaji-ny | they person here see-PAST", "r158_past_they_person_here", ["jana", "bama", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the man here.", "Jana dingkar yaluy nyajin.", "jana dingkar yaluy nyaji-ny | they man here see-PAST", "r158_past_they_man_here", ["jana", "dingkar", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(33, "They saw the woman here.", "Jana jalbu yaluy nyajin.", "jana jalbu yaluy nyaji-ny | they woman here see-PAST", "r158_past_they_woman_here", ["jana", "jalbu", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(34, "They saw the child here.", "Jana karrkay yaluy nyajin.", "jana karrkay yaluy nyaji-ny | they child here see-PAST", "r158_past_they_child_here", ["jana", "karrkay", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; child noun only."),
    row(35, "They saw the mother here.", "Jana ngamu yaluy nyajin.", "jana ngamu yaluy nyaji-ny | they mother here see-PAST", "r158_past_they_mother_here", ["jana", "ngamu", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; mother noun only."),
    row(36, "They saw the father here.", "Jana nganjan yaluy nyajin.", "jana nganjan yaluy nyaji-ny | they father here see-PAST", "r158_past_they_father_here", ["jana", "nganjan", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; father noun only."),
    row(37, "They saw the friend here.", "Jana jawun yaluy nyajin.", "jana jawun yaluy nyaji-ny | they friend here see-PAST", "r158_past_they_friend_here", ["jana", "jawun", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; friend sense only."),
    row(38, "They saw the husband here.", "Jana dunyu yaluy nyajin.", "jana dunyu yaluy nyaji-ny | they husband here see-PAST", "r158_past_they_husband_here", ["jana", "dunyu", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; husband noun only."),
    row(39, "They saw the young man here.", "Jana warru yaluy nyajin.", "jana warru yaluy nyaji-ny | they young.man here see-PAST", "r158_past_they_young_man_here", ["jana", "warru", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; young-man noun only."),
    row(40, "They saw the old man here.", "Jana wulman yaluy nyajin.", "jana wulman yaluy nyaji-ny | they old.man here see-PAST", "r158_past_they_old_man_here", ["jana", "wulman", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; old-man sense only."),
    row(41, "We see the person there.", "Ngana bama yinyay nyajil.", "ngana bama yinyay nyaji-l | we person there see-NONPAST", "r158_present_we_person_there", ["ngana", "bama", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support."),
    row(42, "We see the man there.", "Ngana dingkar yinyay nyajil.", "ngana dingkar yinyay nyaji-l | we man there see-NONPAST", "r158_present_we_man_there", ["ngana", "dingkar", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; dingkar object bare."),
    row(43, "We see the woman there.", "Ngana jalbu yinyay nyajil.", "ngana jalbu yinyay nyaji-l | we woman there see-NONPAST", "r158_present_we_woman_there", ["ngana", "jalbu", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; jalbu object bare."),
    row(44, "We see the child there.", "Ngana karrkay yinyay nyajil.", "ngana karrkay yinyay nyaji-l | we child there see-NONPAST", "r158_present_we_child_there", ["ngana", "karrkay", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; child noun only."),
    row(45, "We see the mother there.", "Ngana ngamu yinyay nyajil.", "ngana ngamu yinyay nyaji-l | we mother there see-NONPAST", "r158_present_we_mother_there", ["ngana", "ngamu", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; mother noun only."),
    row(46, "We see the father there.", "Ngana nganjan yinyay nyajil.", "ngana nganjan yinyay nyaji-l | we father there see-NONPAST", "r158_present_we_father_there", ["ngana", "nganjan", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; father noun only."),
    row(47, "We see the friend there.", "Ngana jawun yinyay nyajil.", "ngana jawun yinyay nyaji-l | we friend there see-NONPAST", "r158_present_we_friend_there", ["ngana", "jawun", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; friend sense only."),
    row(48, "We see the husband there.", "Ngana dunyu yinyay nyajil.", "ngana dunyu yinyay nyaji-l | we husband there see-NONPAST", "r158_present_we_husband_there", ["ngana", "dunyu", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; husband noun only."),
    row(49, "We see the young man there.", "Ngana warru yinyay nyajil.", "ngana warru yinyay nyaji-l | we young.man there see-NONPAST", "r158_present_we_young_man_there", ["ngana", "warru", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; young-man noun only."),
    row(50, "We see the old man there.", "Ngana wulman yinyay nyajil.", "ngana wulman yinyay nyaji-l | we old.man there see-NONPAST", "r158_present_we_old_man_there", ["ngana", "wulman", "yinyay", "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)
        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("r158_"):
            issues.append(f"{label}: Rule 158 frame must start with r158_")
        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 158")
        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 158 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 158")
        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 158")
        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:
                issues.append(f"{label}: Rule 158 deictic rows require yaluy")
            if "here" not in english_low:
                issues.append(f"{label}: deictic rows must translate yaluy as here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 158 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 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 158 draft: construction consolidation after Rule 157", "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 158 source pass retained the Rule 157 human/kin targets bama, dingkar, jalbu, karrkay, ngamu, "
            "nganjan, jawun, dunyu, warru, and wulman; 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 noun/pronoun/deictic/nyaji readback; sqlite lexeme readback",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail=(
            "Rule 158 is a construction consolidation pass for bare yaluy deictic identification and deictic-supported "
            "perception frames. It excludes target case forms, compounds, possessives, kin plurals, address forms, "
            "marriage/change-of-state, avoidance, travel, food, conflict, work, teaching, asking, 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_200.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_200.py static scan", artifact_path="batch_scripts/bank_200.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 158 human/kin construction-consolidation rows.",
                 command="python3 batch_scripts/bank_200.py", artifact_path="batch_scripts/bank_200.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())
