#!/usr/bin/env python3
"""Bank batch-244: Rule 202 deictic sound-reference consolidation."""

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-244"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-244-deictic-sound-reference-consolidation-after-rule201-process.md"

TARGET_HEADS = {
    "kawal": "cooee",
    "ngawungkal": "halloo",
    "ngulnkul": "hum",
    "nyinja": "grunt",
    "wungka": "wail",
    "kandarr": "belch",
    "ngangkun": "hiccups",
    "wankun": "hiccoughs",
    "warimaji": "yawn",
    "kunji": "sneeze",
}
SUPPORT = {"yaluy", "yinyay", "yinya"}
DENY_KUKU = {
    "jangkuy", "kankar", "nginja", "numburr", "yanja", "kadil", "kuwimbur", "ngangkurr", "ngingkirr",
    "wulngku", "burri", "kuku", "jawarr", "jalbubun", "ngukal", "nyirray", "yukurr", "yilal",
    "bama", "dingkar", "jalbu", "kaya", "bibiki", "yarraman", "buliki", "ngawa", "karrkay",
    "mayi", "minya", "nuka", "nukan", "nukal", "waju", "wajun", "yurmbi", "warrmba", "warrmban",
    "nyaji-l", "nyajil", "nyajin", "badi", "badin", "yirrka", "yirrkan", "balka", "balkan",
    "wuna", "wunan", "dunga", "dungan",
    "bubu", "bayan", "bana", "juku", "kurrun", "jinjajalka", "kurunkal", "madu", "marngkil",
    "marrabal", "milbarakal", "mungari", "wurmbariji", "wuymbariji",
    "yala", "yanyu",
}
DENY_ENGLISH = (
    "hear", "heard", "hearing", "listen", "listening", "perceive", "perceived", "see", "saw",
    "chew", "chewing", "clap", "rattle", "rattling", "rustle", "rustling", "whistle", "bark", "barking",
    "song", "sing", "singing", "call", "calling", "shout", "shouting", "cry", "crying", "scream", "screaming",
    "distress", "mourn", "mourning", "death", "dead", "woman", "man", "person", "child", "dog", "pig", "horse",
    "animal", "bird", "motor", "truck", "food", "eat", "eating", "mouth", "teeth", "ear", "body", "sick",
    "sickness", "ill", "illness", "medicine", "story", "country", "place", "tree", "wood", "source", "make",
    "making", "do", "does", "did",
)


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, 3, js(words), js([]), evidence, "0.86")


ROWS = [
    row(1, "The cooee is here.", "Kawal yaluy.", "kawal yaluy | cooee here", "r202_here_kawal", ["kawal", "yaluy"], "Dictionary kawal 'cooee'; Patz 3.7 yaluy 'here'."),
    row(2, "The halloo is here.", "Ngawungkal yaluy.", "ngawungkal yaluy | halloo here", "r202_here_ngawungkal", ["ngawungkal", "yaluy"], "Dictionary ngawungkal 'halloo'; local demonstrative support only."),
    row(3, "The hum is here.", "Ngulnkul yaluy.", "ngulnkul yaluy | hum here", "r202_here_ngulnkul", ["ngulnkul", "yaluy"], "Dictionary ngulnkul 'hum'; no sound-making event."),
    row(4, "The grunt is here.", "Nyinja yaluy.", "nyinja yaluy | grunt here", "r202_here_nyinja", ["nyinja", "yaluy"], "Dictionary nyinja 'grunt'; no source-animal row."),
    row(5, "The wail is here.", "Wungka yaluy.", "wungka yaluy | wail here", "r202_here_wungka", ["wungka", "yaluy"], "Dictionary wungka 'wail'; no distress narrative."),
    row(6, "The belch is here.", "Kandarr yaluy.", "kandarr yaluy | belch here", "r202_here_kandarr", ["kandarr", "yaluy"], "Dictionary kandarr 'belch/burp'; no source body-state row."),
    row(7, "The hiccups are here.", "Ngangkun yaluy.", "ngangkun yaluy | hiccups here", "r202_here_ngangkun", ["ngangkun", "yaluy"], "Dictionary ngangkun 'hiccups/hiccoughs'; no illness row."),
    row(8, "The hiccoughs are here.", "Wankun yaluy.", "wankun yaluy | hiccoughs here", "r202_here_wankun", ["wankun", "yaluy"], "Dictionary wankun 'hiccoughs'; no illness row."),
    row(9, "The yawn is here.", "Warimaji yaluy.", "warimaji yaluy | yawn here", "r202_here_warimaji", ["warimaji", "yaluy"], "Dictionary warimaji 'yawn'; no source-person event."),
    row(10, "The sneeze is here.", "Kunji yaluy.", "kunji yaluy | sneeze here", "r202_here_kunji", ["kunji", "yaluy"], "Dictionary kunji 'sneeze'; no sickness row."),
    row(11, "The cooee is there.", "Kawal yinyay.", "kawal yinyay | cooee there", "r202_there_kawal", ["kawal", "yinyay"], "Dictionary kawal 'cooee'; Patz 3.7 yinyay 'there'."),
    row(12, "The halloo is there.", "Ngawungkal yinyay.", "ngawungkal yinyay | halloo there", "r202_there_ngawungkal", ["ngawungkal", "yinyay"], "Dictionary ngawungkal 'halloo'; no far-away source-person event."),
    row(13, "The hum is there.", "Ngulnkul yinyay.", "ngulnkul yinyay | hum there", "r202_there_ngulnkul", ["ngulnkul", "yinyay"], "Dictionary ngulnkul 'hum'; no tune-making row."),
    row(14, "The grunt is there.", "Nyinja yinyay.", "nyinja yinyay | grunt there", "r202_there_nyinja", ["nyinja", "yinyay"], "Dictionary nyinja 'grunt'; no animal source."),
    row(15, "The wail is there.", "Wungka yinyay.", "wungka yinyay | wail there", "r202_there_wungka", ["wungka", "yinyay"], "Dictionary wungka 'wail'; distress narrative closed."),
    row(16, "The belch is there.", "Kandarr yinyay.", "kandarr yinyay | belch there", "r202_there_kandarr", ["kandarr", "yinyay"], "Dictionary kandarr 'belch/burp'; body-state source closed."),
    row(17, "The hiccups are there.", "Ngangkun yinyay.", "ngangkun yinyay | hiccups there", "r202_there_ngangkun", ["ngangkun", "yinyay"], "Dictionary ngangkun 'hiccups/hiccoughs'; illness reading closed."),
    row(18, "The hiccoughs are there.", "Wankun yinyay.", "wankun yinyay | hiccoughs there", "r202_there_wankun", ["wankun", "yinyay"], "Dictionary wankun 'hiccoughs'; illness reading closed."),
    row(19, "The yawn is there.", "Warimaji yinyay.", "warimaji yinyay | yawn there", "r202_there_warimaji", ["warimaji", "yinyay"], "Dictionary warimaji 'yawn'; no source-person event."),
    row(20, "The sneeze is there.", "Kunji yinyay.", "kunji yinyay | sneeze there", "r202_there_kunji", ["kunji", "yinyay"], "Dictionary kunji 'sneeze'; sickness reading closed."),
    row(21, "That cooee is there.", "Yinya kawal yinyay.", "yinya kawal yinyay | that cooee there", "r202_initial_that_there_kawal", ["yinya", "kawal", "yinyay"], "Patz 4.1 yinya may precede one noun; Patz 3.7 yinyay 'there'."),
    row(22, "That halloo is there.", "Yinya ngawungkal yinyay.", "yinya ngawungkal yinyay | that halloo there", "r202_initial_that_there_ngawungkal", ["yinya", "ngawungkal", "yinyay"], "Initial demonstrative with one sound noun; no source event."),
    row(23, "That hum is there.", "Yinya ngulnkul yinyay.", "yinya ngulnkul yinyay | that hum there", "r202_initial_that_there_ngulnkul", ["yinya", "ngulnkul", "yinyay"], "Initial demonstrative with one sound noun; no sound-making event."),
    row(24, "That grunt is there.", "Yinya nyinja yinyay.", "yinya nyinja yinyay | that grunt there", "r202_initial_that_there_nyinja", ["yinya", "nyinja", "yinyay"], "Initial demonstrative with one sound noun; animal-source row closed."),
    row(25, "That wail is there.", "Yinya wungka yinyay.", "yinya wungka yinyay | that wail there", "r202_initial_that_there_wungka", ["yinya", "wungka", "yinyay"], "Initial demonstrative with one sound noun; distress narrative closed."),
    row(26, "That belch is there.", "Yinya kandarr yinyay.", "yinya kandarr yinyay | that belch there", "r202_initial_that_there_kandarr", ["yinya", "kandarr", "yinyay"], "Initial demonstrative with one sound noun; body-state source closed."),
    row(27, "Those hiccups are there.", "Yinya ngangkun yinyay.", "yinya ngangkun yinyay | those hiccups there", "r202_initial_that_there_ngangkun", ["yinya", "ngangkun", "yinyay"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(28, "Those hiccoughs are there.", "Yinya wankun yinyay.", "yinya wankun yinyay | those hiccoughs there", "r202_initial_that_there_wankun", ["yinya", "wankun", "yinyay"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(29, "That yawn is there.", "Yinya warimaji yinyay.", "yinya warimaji yinyay | that yawn there", "r202_initial_that_there_warimaji", ["yinya", "warimaji", "yinyay"], "Initial demonstrative with one sound noun; source-person event closed."),
    row(30, "That sneeze is there.", "Yinya kunji yinyay.", "yinya kunji yinyay | that sneeze there", "r202_initial_that_there_kunji", ["yinya", "kunji", "yinyay"], "Initial demonstrative with one sound noun; sickness reading closed."),
    row(31, "That cooee is there.", "Kawal yinya yinyay.", "kawal yinya yinyay | cooee that there", "r202_postposed_that_there_kawal", ["kawal", "yinya", "yinyay"], "Patz 4.1 yinya may follow one noun; Rule 200 construction precedent."),
    row(32, "That halloo is there.", "Ngawungkal yinya yinyay.", "ngawungkal yinya yinyay | halloo that there", "r202_postposed_that_there_ngawungkal", ["ngawungkal", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; no source event."),
    row(33, "That hum is there.", "Ngulnkul yinya yinyay.", "ngulnkul yinya yinyay | hum that there", "r202_postposed_that_there_ngulnkul", ["ngulnkul", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; no sound-making event."),
    row(34, "That grunt is there.", "Nyinja yinya yinyay.", "nyinja yinya yinyay | grunt that there", "r202_postposed_that_there_nyinja", ["nyinja", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; animal-source row closed."),
    row(35, "That wail is there.", "Wungka yinya yinyay.", "wungka yinya yinyay | wail that there", "r202_postposed_that_there_wungka", ["wungka", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; distress narrative closed."),
    row(36, "That belch is there.", "Kandarr yinya yinyay.", "kandarr yinya yinyay | belch that there", "r202_postposed_that_there_kandarr", ["kandarr", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; body-state source closed."),
    row(37, "Those hiccups are there.", "Ngangkun yinya yinyay.", "ngangkun yinya yinyay | hiccups those there", "r202_postposed_that_there_ngangkun", ["ngangkun", "yinya", "yinyay"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(38, "Those hiccoughs are there.", "Wankun yinya yinyay.", "wankun yinya yinyay | hiccoughs those there", "r202_postposed_that_there_wankun", ["wankun", "yinya", "yinyay"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(39, "That yawn is there.", "Warimaji yinya yinyay.", "warimaji yinya yinyay | yawn that there", "r202_postposed_that_there_warimaji", ["warimaji", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; source-person event closed."),
    row(40, "That sneeze is there.", "Kunji yinya yinyay.", "kunji yinya yinyay | sneeze that there", "r202_postposed_that_there_kunji", ["kunji", "yinya", "yinyay"], "Postposed demonstrative with one sound noun; sickness reading closed."),
    row(41, "That cooee is here.", "Yinya kawal yaluy.", "yinya kawal yaluy | that cooee here", "r202_initial_that_here_kawal", ["yinya", "kawal", "yaluy"], "Initial demonstrative with local yaluy support."),
    row(42, "That halloo is here.", "Yinya ngawungkal yaluy.", "yinya ngawungkal yaluy | that halloo here", "r202_initial_that_here_ngawungkal", ["yinya", "ngawungkal", "yaluy"], "Initial demonstrative with local yaluy support; no source event."),
    row(43, "That hum is here.", "Yinya ngulnkul yaluy.", "yinya ngulnkul yaluy | that hum here", "r202_initial_that_here_ngulnkul", ["yinya", "ngulnkul", "yaluy"], "Initial demonstrative with local yaluy support; no sound-making event."),
    row(44, "That grunt is here.", "Yinya nyinja yaluy.", "yinya nyinja yaluy | that grunt here", "r202_initial_that_here_nyinja", ["yinya", "nyinja", "yaluy"], "Initial demonstrative with local yaluy support; animal-source row closed."),
    row(45, "That wail is here.", "Yinya wungka yaluy.", "yinya wungka yaluy | that wail here", "r202_initial_that_here_wungka", ["yinya", "wungka", "yaluy"], "Initial demonstrative with local yaluy support; distress narrative closed."),
    row(46, "That belch is here.", "Yinya kandarr yaluy.", "yinya kandarr yaluy | that belch here", "r202_initial_that_here_kandarr", ["yinya", "kandarr", "yaluy"], "Initial demonstrative with local yaluy support; body-state source closed."),
    row(47, "Those hiccups are here.", "Yinya ngangkun yaluy.", "yinya ngangkun yaluy | those hiccups here", "r202_initial_that_here_ngangkun", ["yinya", "ngangkun", "yaluy"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(48, "Those hiccoughs are here.", "Yinya wankun yaluy.", "yinya wankun yaluy | those hiccoughs here", "r202_initial_that_here_wankun", ["yinya", "wankun", "yaluy"], "Patz 3.7 yinya may imply plural by context; illness reading closed."),
    row(49, "That yawn is here.", "Yinya warimaji yaluy.", "yinya warimaji yaluy | that yawn here", "r202_initial_that_here_warimaji", ["yinya", "warimaji", "yaluy"], "Initial demonstrative with local yaluy support; source-person event closed."),
    row(50, "That sneeze is here.", "Yinya kunji yaluy.", "yinya kunji yaluy | that sneeze here", "r202_initial_that_here_kunji", ["yinya", "kunji", "yaluy"], "Initial demonstrative with local yaluy support; sickness reading closed."),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", low) is not None


def has_target_morphology(low: str, head: str) -> bool:
    suffixes = "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|baja|bungal|bungan|mal|man|rriny"
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:{suffixes})\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("r202_"):
            issues.append(f"{label}: Rule 202 frame must start with r202_")
        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 202")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied previous-field/source/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 202 sound target, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        for support in SUPPORT:
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if any(has_token(low, bad) for bad in ("nyaji-l", "nyajil", "nyajin", "nyaji")):
            issues.append(f"{label}: Rule 202 has no nyaji-l/hearing verb")
        if 1 <= seq <= 10 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.")):
            issues.append(f"{label}: rows 1-10 require TARGET yaluy")
        if 11 <= seq <= 20 and (has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 11-20 require TARGET yinyay")
        if 21 <= seq <= 30 and (not low.startswith("yinya ") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 21-30 require Yinya TARGET yinyay")
        if 31 <= seq <= 40 and (low.startswith("yinya ") or has_token(low, "yaluy") or not low.endswith(" yinya yinyay.")):
            issues.append(f"{label}: rows 31-40 require TARGET yinya yinyay")
        if 41 <= seq <= 50 and (not low.startswith("yinya ") or has_token(low, "yinyay") or not low.endswith(" yaluy.")):
            issues.append(f"{label}: rows 41-50 require Yinya TARGET yaluy")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied source/event/body-state 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 202 draft: deictic sound-reference construction consolidation after Rule 201",
                "operator-guide-2026-07-08",
                "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 202 source pass retained the ten Rule 201 sound nouns and shifted them into deictic/presentational frames. Patz 3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'; Patz 4.1 supports yinya before or after a single noun.",
        command="grammar.md exact readback for Patz 3.7 and 4.1; dictionary.yaml readback for yinya/yaluy/yinyay; corpus duplicate preflight",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail="Rule 202 is construction consolidation only: bare sound nouns in here/there/that presentational frames. It excludes nyaji-l, hearing/listening/perception rows, sound-making events, source persons/animals, illness/body-state/distress narratives, proximal yala/yanyu, and target morphology.",
        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 over all 50 planned deictic sound-reference surfaces returned no accepted/revised/under_review collisions.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_244.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guard passed: exactly 50 unique surfaces; exactly one retained sound target per row; support heads present in words_used; no loans; no nyaji-l/hearing verb; no previous sound-batch, tree-reference, proximal-demonstrative, source/event/body-state English, or target morphology leakage; and correct five-frame distribution.",
        command="python3 batch_scripts/bank_244.py pre-bank scan",
        artifact_path="batch_scripts/bank_244.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",
                NOW,
                NOW,
            )
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

    count = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=?", (batch_id,)).fetchone()[0]
    under_review = db.execute(
        "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'",
        (batch_id,),
    ).fetchone()[0]
    verified = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    print(f"banked {LABEL}: rows={count}, under_review={under_review}, verified_before_close={verified}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
