#!/usr/bin/env python3
"""Bank batch-213: Rule 171 shellfish reference lexical expansion after Rule 170."""

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

TARGET_HEADS = {
    "balungkul": "shell back snail",
    "juwarru": "mud oyster",
    "marakal": "spider shell",
    "marku": "species of oyster",
    "marubu": "species of oyster",
    "munji": "big clam shell",
    "ngulumuku": "seashell",
    "wukuju": "freshwater prawn",
    "wuybur": "jellyfish",
    "yulba": "large round oyster",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "baymbay", "dakaldakal", "darkay", "jalan", "julul", "kaduy", "kajarrbi", "karraway",
    "karruku", "kiju", "kulil", "kunkun", "kurrija", "kuyalin", "jirrum", "marrkabina",
    "mukirr", "ngajay", "ngalngal", "ngarrakaja", "nikar", "nuwi", "wakal", "wuli-wuli",
    "wurru-bulan", "wurrul", "mili", "manin", "bangkan", "nuka", "nukan", "waju", "wajun",
    "daya", "dajin", "daji", "dinda", "dindan", "wandil", "wandin", "bayka", "baykal",
}
DENY_ENGLISH = (
    "edible", "eat", "eats", "ate", "eaten", "food", "meat", "bait", "catch", "catches",
    "caught", "gather", "gathers", "gathered", "cook", "cooks", "cooked", "fry", "fried",
    "roast", "roasted", "boil", "boiled", "clean", "cleaned", "tobacco", "rock", "rocks",
    "mangrove", "mangroves", "cling", "clings", "clung", "night", "nocturnal", "hole", "holes",
    "leg", "legs", "touch", "sting", "stings", "stung", "danger", "dangerous", "preparation",
)


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 shell back snail is here.", "Balungkul yaluy.", "balungkul yaluy | shell.back.snail here", "r171_deictic_balungkul_here", ["balungkul", "yaluy"], "Rule 171 admits balungkul as shell back snail; reference only."),
    row(2, "The marku species of oyster is here.", "Marku yaluy.", "marku yaluy | species.of.oyster here", "r171_deictic_marku_here", ["marku", "yaluy"], "Rule 171 admits marku as species of oyster; reference only."),
    row(3, "The mud oyster is here.", "Juwarru yaluy.", "juwarru yaluy | mud.oyster here", "r171_deictic_juwarru_here", ["juwarru", "yaluy"], "Rule 171 admits juwarru as mud oyster; no habitat or comparison row."),
    row(4, "The spider shell is here.", "Marakal yaluy.", "marakal yaluy | spider.shell here", "r171_deictic_marakal_here", ["marakal", "yaluy"], "Rule 171 admits marakal as spider shell; reference only."),
    row(5, "The marubu species of oyster is here.", "Marubu yaluy.", "marubu yaluy | species.of.oyster here", "r171_deictic_marubu_here", ["marubu", "yaluy"], "Rule 171 admits marubu as species of oyster; reference only."),
    row(6, "The big clam shell is here.", "Munji yaluy.", "munji yaluy | big.clam.shell here", "r171_deictic_munji_here", ["munji", "yaluy"], "Rule 171 admits munji as big clam shell; no use row."),
    row(7, "The seashell is here.", "Ngulumuku yaluy.", "ngulumuku yaluy | seashell here", "r171_deictic_ngulumuku_here", ["ngulumuku", "yaluy"], "Rule 171 admits ngulumuku as seashell; reference only."),
    row(8, "The freshwater prawn is here.", "Wukuju yaluy.", "wukuju yaluy | freshwater.prawn here", "r171_deictic_wukuju_here", ["wukuju", "yaluy"], "Rule 171 admits wukuju as freshwater prawn; no size/leg row."),
    row(9, "The jellyfish is here.", "Wuybur yaluy.", "wuybur yaluy | jellyfish here", "r171_deictic_wuybur_here", ["wuybur", "yaluy"], "Rule 171 admits wuybur as jellyfish; no sting/touch row."),
    row(10, "The large round oyster is here.", "Yulba yaluy.", "yulba yaluy | large.round.oyster here", "r171_deictic_yulba_here", ["yulba", "yaluy"], "Rule 171 admits yulba as large round oyster; reference only."),
    row(11, "I see the shell back snail.", "Ngayu balungkul nyajil.", "ngayu balungkul nyaji-l | I shell.back.snail see-NONPAST", "r171_present_i_balungkul", ["ngayu", "balungkul", "nyaji-l"], "Pronoun A bare; balungkul object bare."),
    row(12, "I see the marku species of oyster.", "Ngayu marku nyajil.", "ngayu marku nyaji-l | I species.of.oyster see-NONPAST", "r171_present_i_marku", ["ngayu", "marku", "nyaji-l"], "Pronoun A bare; marku object bare."),
    row(13, "I see the mud oyster.", "Ngayu juwarru nyajil.", "ngayu juwarru nyaji-l | I mud.oyster see-NONPAST", "r171_present_i_juwarru", ["ngayu", "juwarru", "nyaji-l"], "Pronoun A bare; no habitat/comparison row."),
    row(14, "I see the spider shell.", "Ngayu marakal nyajil.", "ngayu marakal nyaji-l | I spider.shell see-NONPAST", "r171_present_i_marakal", ["ngayu", "marakal", "nyaji-l"], "Pronoun A bare; marakal object bare."),
    row(15, "I see the marubu species of oyster.", "Ngayu marubu nyajil.", "ngayu marubu nyaji-l | I species.of.oyster see-NONPAST", "r171_present_i_marubu", ["ngayu", "marubu", "nyaji-l"], "Pronoun A bare; marubu object bare."),
    row(16, "I see the big clam shell.", "Ngayu munji nyajil.", "ngayu munji nyaji-l | I big.clam.shell see-NONPAST", "r171_present_i_munji", ["ngayu", "munji", "nyaji-l"], "Pronoun A bare; no use row."),
    row(17, "I see the seashell.", "Ngayu ngulumuku nyajil.", "ngayu ngulumuku nyaji-l | I seashell see-NONPAST", "r171_present_i_ngulumuku", ["ngayu", "ngulumuku", "nyaji-l"], "Pronoun A bare; ngulumuku object bare."),
    row(18, "I see the freshwater prawn.", "Ngayu wukuju nyajil.", "ngayu wukuju nyaji-l | I freshwater.prawn see-NONPAST", "r171_present_i_wukuju", ["ngayu", "wukuju", "nyaji-l"], "Pronoun A bare; no size/leg row."),
    row(19, "I see the jellyfish.", "Ngayu wuybur nyajil.", "ngayu wuybur nyaji-l | I jellyfish see-NONPAST", "r171_present_i_wuybur", ["ngayu", "wuybur", "nyaji-l"], "Pronoun A bare; no sting/touch row."),
    row(20, "I see the large round oyster.", "Ngayu yulba nyajil.", "ngayu yulba nyaji-l | I large.round.oyster see-NONPAST", "r171_present_i_yulba", ["ngayu", "yulba", "nyaji-l"], "Pronoun A bare; yulba object bare."),
    row(21, "You see the shell back snail there.", "Yundu balungkul yinyay nyajil.", "yundu balungkul yinyay nyaji-l | you shell.back.snail there see-NONPAST", "r171_present_you_balungkul_there", ["yundu", "balungkul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(22, "You see the marku species of oyster there.", "Yundu marku yinyay nyajil.", "yundu marku yinyay nyaji-l | you species.of.oyster there see-NONPAST", "r171_present_you_marku_there", ["yundu", "marku", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(23, "You see the mud oyster there.", "Yundu juwarru yinyay nyajil.", "yundu juwarru yinyay nyaji-l | you mud.oyster there see-NONPAST", "r171_present_you_juwarru_there", ["yundu", "juwarru", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no habitat/comparison row."),
    row(24, "You see the spider shell there.", "Yundu marakal yinyay nyajil.", "yundu marakal yinyay nyaji-l | you spider.shell there see-NONPAST", "r171_present_you_marakal_there", ["yundu", "marakal", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(25, "You see the marubu species of oyster there.", "Yundu marubu yinyay nyajil.", "yundu marubu yinyay nyaji-l | you species.of.oyster there see-NONPAST", "r171_present_you_marubu_there", ["yundu", "marubu", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the big clam shell there.", "Yundu munji yinyay nyajil.", "yundu munji yinyay nyaji-l | you big.clam.shell there see-NONPAST", "r171_present_you_munji_there", ["yundu", "munji", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no use row."),
    row(27, "You see the seashell there.", "Yundu ngulumuku yinyay nyajil.", "yundu ngulumuku yinyay nyaji-l | you seashell there see-NONPAST", "r171_present_you_ngulumuku_there", ["yundu", "ngulumuku", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the freshwater prawn there.", "Yundu wukuju yinyay nyajil.", "yundu wukuju yinyay nyaji-l | you freshwater.prawn there see-NONPAST", "r171_present_you_wukuju_there", ["yundu", "wukuju", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no size/leg row."),
    row(29, "You see the jellyfish there.", "Yundu wuybur yinyay nyajil.", "yundu wuybur yinyay nyaji-l | you jellyfish there see-NONPAST", "r171_present_you_wuybur_there", ["yundu", "wuybur", "yinyay", "nyaji-l"], "Second-person pronoun A bare; no sting/touch row."),
    row(30, "You see the large round oyster there.", "Yundu yulba yinyay nyajil.", "yundu yulba yinyay nyaji-l | you large.round.oyster there see-NONPAST", "r171_present_you_yulba_there", ["yundu", "yulba", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the shell back snail there.", "Jana balungkul yinyay nyajin.", "jana balungkul yinyay nyaji-ny | they shell.back.snail there see-PAST", "r171_past_they_balungkul_there", ["jana", "balungkul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the marku species of oyster there.", "Jana marku yinyay nyajin.", "jana marku yinyay nyaji-ny | they species.of.oyster there see-PAST", "r171_past_they_marku_there", ["jana", "marku", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(33, "They saw the mud oyster there.", "Jana juwarru yinyay nyajin.", "jana juwarru yinyay nyaji-ny | they mud.oyster there see-PAST", "r171_past_they_juwarru_there", ["jana", "juwarru", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no habitat/comparison row."),
    row(34, "They saw the spider shell there.", "Jana marakal yinyay nyajin.", "jana marakal yinyay nyaji-ny | they spider.shell there see-PAST", "r171_past_they_marakal_there", ["jana", "marakal", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(35, "They saw the marubu species of oyster there.", "Jana marubu yinyay nyajin.", "jana marubu yinyay nyaji-ny | they species.of.oyster there see-PAST", "r171_past_they_marubu_there", ["jana", "marubu", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(36, "They saw the big clam shell there.", "Jana munji yinyay nyajin.", "jana munji yinyay nyaji-ny | they big.clam.shell there see-PAST", "r171_past_they_munji_there", ["jana", "munji", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no use row."),
    row(37, "They saw the seashell there.", "Jana ngulumuku yinyay nyajin.", "jana ngulumuku yinyay nyaji-ny | they seashell there see-PAST", "r171_past_they_ngulumuku_there", ["jana", "ngulumuku", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(38, "They saw the freshwater prawn there.", "Jana wukuju yinyay nyajin.", "jana wukuju yinyay nyaji-ny | they freshwater.prawn there see-PAST", "r171_past_they_wukuju_there", ["jana", "wukuju", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no size/leg row."),
    row(39, "They saw the jellyfish there.", "Jana wuybur yinyay nyajin.", "jana wuybur yinyay nyaji-ny | they jellyfish there see-PAST", "r171_past_they_wuybur_there", ["jana", "wuybur", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; no sting/touch row."),
    row(40, "They saw the large round oyster there.", "Jana yulba yinyay nyajin.", "jana yulba yinyay nyaji-ny | they large.round.oyster there see-PAST", "r171_past_they_yulba_there", ["jana", "yulba", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(41, "We see the shell back snail here.", "Ngana balungkul yaluy nyajil.", "ngana balungkul yaluy nyaji-l | we shell.back.snail here see-NONPAST", "r171_present_we_balungkul_here", ["ngana", "balungkul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(42, "We see the marku species of oyster here.", "Ngana marku yaluy nyajil.", "ngana marku yaluy nyaji-l | we species.of.oyster here see-NONPAST", "r171_present_we_marku_here", ["ngana", "marku", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(43, "We see the mud oyster here.", "Ngana juwarru yaluy nyajil.", "ngana juwarru yaluy nyaji-l | we mud.oyster here see-NONPAST", "r171_present_we_juwarru_here", ["ngana", "juwarru", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no habitat/comparison row."),
    row(44, "We see the spider shell here.", "Ngana marakal yaluy nyajil.", "ngana marakal yaluy nyaji-l | we spider.shell here see-NONPAST", "r171_present_we_marakal_here", ["ngana", "marakal", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(45, "We see the marubu species of oyster here.", "Ngana marubu yaluy nyajil.", "ngana marubu yaluy nyaji-l | we species.of.oyster here see-NONPAST", "r171_present_we_marubu_here", ["ngana", "marubu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(46, "We see the big clam shell here.", "Ngana munji yaluy nyajil.", "ngana munji yaluy nyaji-l | we big.clam.shell here see-NONPAST", "r171_present_we_munji_here", ["ngana", "munji", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no use row."),
    row(47, "We see the seashell here.", "Ngana ngulumuku yaluy nyajil.", "ngana ngulumuku yaluy nyaji-l | we seashell here see-NONPAST", "r171_present_we_ngulumuku_here", ["ngana", "ngulumuku", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(48, "We see the freshwater prawn here.", "Ngana wukuju yaluy nyajil.", "ngana wukuju yaluy nyaji-l | we freshwater.prawn here see-NONPAST", "r171_present_we_wukuju_here", ["ngana", "wukuju", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no size/leg row."),
    row(49, "We see the jellyfish here.", "Ngana wuybur yaluy nyajil.", "ngana wuybur yaluy nyaji-l | we jellyfish here see-NONPAST", "r171_present_we_wuybur_here", ["ngana", "wuybur", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; no sting/touch row."),
    row(50, "We see the large round oyster here.", "Ngana yulba yaluy nyajil.", "ngana yulba yaluy nyaji-l | we large.round.oyster here see-NONPAST", "r171_present_we_yulba_here", ["ngana", "yulba", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
]


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("r171_"):
            issues.append(f"{label}: Rule 171 frame must start with r171_")
        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 171")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied rejected/use 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 171 target head, 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.replace(" ", ".") not in analysis and selected not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 171 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 171 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":
                issues.append(f"{label}: rows 11-20 require ngayu")
            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 use/event/habitat 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 171 draft: shellfish reference lexical expansion after Rule 170", "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 171 source pass selected ten unused shellfish/crustacean-domain reference heads: balungkul, juwarru, marakal, marku, marubu, munji, ngulumuku, wukuju, wuybur, and yulba. Dictionary exact readback confirmed selected senses. Patz readback found no target-head conflicts and reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Boundary-aware corpus readback found zero accepted/revised/under_review rows for selected targets. Jirrum was retired after initial lint because the current corpus phonotactic guard rejects final -m.",
                 command="structured dictionary readback; rg grammar readback; sqlite boundary-aware corpus 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 171 is a lexical shellfish-reference pass for ten bare target heads. It excludes eating, edible status, bait, catching, gathering, cooking, cleaning, roasting, boiling, habitat, clinging, movement, body-part behavior, sting, touch, danger, preparation, use, target case, target compounds, possession, and event claims.",
                 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_213.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one Rule 171 shellfish target per row; all targets bare; no loans; no rejected/use/event/habitat tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_213.py static scan", artifact_path="batch_scripts/bank_213.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, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()

    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={len(ROWS)}, under_review={under_review}, verified_before_close={verified}")
    return 0


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