#!/usr/bin/env python3
"""Bank batch-265: Rule 223 second shellfish/crustacean-reference lexical expansion."""

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

TARGET_HEADS = {
    "kiju": "mudcrab",
    "dakaldakal": "trocus shell",
    "kajarrbi": "clam shell",
    "kunkun": "periwinkle",
    "kurrija": "octopus",
    "ngajay": "crayfish",
    "nikar": "oyster",
    "wakal": "prawn",
    "wuli-wuli": "soldier crab",
    "wurrul": "shellfish",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    # Rule 213 shellfish/crustacean targets.
    "baymbay", "darkay", "kaduy", "karraway", "karruku", "kulil", "kuyalin",
    "marrkabina", "ngarrakaja", "nuwi",
    # Rejected/deferred shellfish, fish, ray, and homograph candidates.
    "jalan", "jirrum", "mukirr", "yidi", "yidilnyul", "bilmbin", "walkan", "badibu", "bilaji",
    "ngarmu", "yalnganji", "yawu", "juwarru", "wurru-bulan", "wukuju", "mili",
    "marakal", "marku", "marubu", "munji", "ngulumuku", "wuybur", "yulba", "julul",
    "ngalngal", "jarramali", "dikarra",
    # Recent insect, bird, reptile/amphibian, mammal, and fish targets.
    "kira-kira", "kandal", "kinga", "mulma", "biringal", "birinjil", "kurrmbal",
    "nganjamu", "kurran", "ngirran", "bajal", "jiwurrmal", "jangkan", "karunkurr",
    "jurriyan", "kuludu", "kurrbal", "jaka", "kalkuy", "wakuka", "bajuy", "bilngkumu",
    "binanjal", "bindimu", "bubal", "jijirrbay", "kabul", "kalajarr", "kundurr",
    "yuday", "bala", "darrba", "jarrabina", "jayju", "jungarr", "kukur", "mali",
    "murramu", "ngumbi", "yawa", "baban", "bububay", "ngalkun", "barrbal", "jalkay",
    "janbal", "jijirr", "kurrubal", "murraja",
}
DENY_ENGLISH = (
    "edible", "food", "eat", "eating", "eaten", "fry", "fried", "cook", "cooking",
    "roast", "roasting", "boil", "boiling", "clean", "cleaning", "bait", "use", "used",
    "gather", "gathering", "collect", "collecting", "catch", "catching", "fish", "fishing",
    "spear", "spearing", "net", "netting", "sea", "reef", "rock", "night", "habitat",
    "water", "freshwater", "brackish", "river", "creek", "mangrove", "sting", "burn",
    "burning", "barb", "ray", "stingray", "manta", "weapon", "body-part", "body part",
    "story", "place", "place-name", "homograph", "lobster", "variant", "secondary", "many",
    "support inflection", "plural",
)


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


EVIDENCE = {
    "kiju": "Dictionary kiju noun 'mudcrab'. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "dakaldakal": "Dictionary dakaldakal noun 'trocus shell'; lexicalized solid reduplicated headword, not productive reduplication. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "kajarrbi": "Dictionary kajarrbi noun 'clam shell' / giant clam; shell label stays lexical. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "kunkun": "Dictionary kunkun noun 'periwinkle'; lexicalized solid reduplicated headword, not productive reduplication. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "kurrija": "Dictionary kurrija noun 'octopus'. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "ngajay": "Dictionary ngajay noun 'crayfish'; source note not eaten stays lexical only. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "nikar": "Dictionary nikar noun 'oyster'; shallow-water/rock habitat prose not opened. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "wakal": "Dictionary wakal noun 'prawn'; lobster variant not opened. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "wuli-wuli": "Dictionary wuli-wuli noun 'soldier crab'; lexicalized hyphenated headword, not productive reduplication. Patz section 3.1 fauna noun and section 3.7 deictic support.",
    "wurrul": "Dictionary wurrul noun 'shellfish' / species of shellfish. Patz section 3.1 fauna noun and section 3.7 deictic support.",
}


ROWS = [
    row(1, "The mudcrab is here.", "Kiju yaluy.", "kiju yaluy | mudcrab here", "r223_shellfish_ref_here_kiju", ["kiju", "yaluy"], EVIDENCE["kiju"]),
    row(2, "The trocus shell is here.", "Dakaldakal yaluy.", "dakaldakal yaluy | trocus.shell here", "r223_shellfish_ref_here_dakaldakal", ["dakaldakal", "yaluy"], EVIDENCE["dakaldakal"]),
    row(3, "The clam shell is here.", "Kajarrbi yaluy.", "kajarrbi yaluy | clam.shell here", "r223_shellfish_ref_here_kajarrbi", ["kajarrbi", "yaluy"], EVIDENCE["kajarrbi"]),
    row(4, "The periwinkle is here.", "Kunkun yaluy.", "kunkun yaluy | periwinkle here", "r223_shellfish_ref_here_kunkun", ["kunkun", "yaluy"], EVIDENCE["kunkun"]),
    row(5, "The octopus is here.", "Kurrija yaluy.", "kurrija yaluy | octopus here", "r223_shellfish_ref_here_kurrija", ["kurrija", "yaluy"], EVIDENCE["kurrija"]),
    row(6, "The crayfish is here.", "Ngajay yaluy.", "ngajay yaluy | crayfish here", "r223_shellfish_ref_here_ngajay", ["ngajay", "yaluy"], EVIDENCE["ngajay"]),
    row(7, "The oyster is here.", "Nikar yaluy.", "nikar yaluy | oyster here", "r223_shellfish_ref_here_nikar", ["nikar", "yaluy"], EVIDENCE["nikar"]),
    row(8, "The prawn is here.", "Wakal yaluy.", "wakal yaluy | prawn here", "r223_shellfish_ref_here_wakal", ["wakal", "yaluy"], EVIDENCE["wakal"]),
    row(9, "The soldier crab is here.", "Wuli-wuli yaluy.", "wuli-wuli yaluy | soldier.crab here", "r223_shellfish_ref_here_wuli_wuli", ["wuli-wuli", "yaluy"], EVIDENCE["wuli-wuli"]),
    row(10, "The shellfish is here.", "Wurrul yaluy.", "wurrul yaluy | shellfish here", "r223_shellfish_ref_here_wurrul", ["wurrul", "yaluy"], EVIDENCE["wurrul"]),
    row(11, "The mudcrab is there.", "Kiju yinyay.", "kiju yinyay | mudcrab there", "r223_shellfish_ref_there_kiju", ["kiju", "yinyay"], EVIDENCE["kiju"]),
    row(12, "The trocus shell is there.", "Dakaldakal yinyay.", "dakaldakal yinyay | trocus.shell there", "r223_shellfish_ref_there_dakaldakal", ["dakaldakal", "yinyay"], EVIDENCE["dakaldakal"]),
    row(13, "The clam shell is there.", "Kajarrbi yinyay.", "kajarrbi yinyay | clam.shell there", "r223_shellfish_ref_there_kajarrbi", ["kajarrbi", "yinyay"], EVIDENCE["kajarrbi"]),
    row(14, "The periwinkle is there.", "Kunkun yinyay.", "kunkun yinyay | periwinkle there", "r223_shellfish_ref_there_kunkun", ["kunkun", "yinyay"], EVIDENCE["kunkun"]),
    row(15, "The octopus is there.", "Kurrija yinyay.", "kurrija yinyay | octopus there", "r223_shellfish_ref_there_kurrija", ["kurrija", "yinyay"], EVIDENCE["kurrija"]),
    row(16, "The crayfish is there.", "Ngajay yinyay.", "ngajay yinyay | crayfish there", "r223_shellfish_ref_there_ngajay", ["ngajay", "yinyay"], EVIDENCE["ngajay"]),
    row(17, "The oyster is there.", "Nikar yinyay.", "nikar yinyay | oyster there", "r223_shellfish_ref_there_nikar", ["nikar", "yinyay"], EVIDENCE["nikar"]),
    row(18, "The prawn is there.", "Wakal yinyay.", "wakal yinyay | prawn there", "r223_shellfish_ref_there_wakal", ["wakal", "yinyay"], EVIDENCE["wakal"]),
    row(19, "The soldier crab is there.", "Wuli-wuli yinyay.", "wuli-wuli yinyay | soldier.crab there", "r223_shellfish_ref_there_wuli_wuli", ["wuli-wuli", "yinyay"], EVIDENCE["wuli-wuli"]),
    row(20, "The shellfish is there.", "Wurrul yinyay.", "wurrul yinyay | shellfish there", "r223_shellfish_ref_there_wurrul", ["wurrul", "yinyay"], EVIDENCE["wurrul"]),
    row(21, "That mudcrab is there.", "Yinya kiju yinyay.", "yinya kiju yinyay | that mudcrab there", "r223_that_shellfish_ref_there_kiju", ["yinya", "kiju", "yinyay"], EVIDENCE["kiju"]),
    row(22, "That trocus shell is there.", "Yinya dakaldakal yinyay.", "yinya dakaldakal yinyay | that trocus.shell there", "r223_that_shellfish_ref_there_dakaldakal", ["yinya", "dakaldakal", "yinyay"], EVIDENCE["dakaldakal"]),
    row(23, "That clam shell is there.", "Yinya kajarrbi yinyay.", "yinya kajarrbi yinyay | that clam.shell there", "r223_that_shellfish_ref_there_kajarrbi", ["yinya", "kajarrbi", "yinyay"], EVIDENCE["kajarrbi"]),
    row(24, "That periwinkle is there.", "Yinya kunkun yinyay.", "yinya kunkun yinyay | that periwinkle there", "r223_that_shellfish_ref_there_kunkun", ["yinya", "kunkun", "yinyay"], EVIDENCE["kunkun"]),
    row(25, "That octopus is there.", "Yinya kurrija yinyay.", "yinya kurrija yinyay | that octopus there", "r223_that_shellfish_ref_there_kurrija", ["yinya", "kurrija", "yinyay"], EVIDENCE["kurrija"]),
    row(26, "That crayfish is there.", "Yinya ngajay yinyay.", "yinya ngajay yinyay | that crayfish there", "r223_that_shellfish_ref_there_ngajay", ["yinya", "ngajay", "yinyay"], EVIDENCE["ngajay"]),
    row(27, "That oyster is there.", "Yinya nikar yinyay.", "yinya nikar yinyay | that oyster there", "r223_that_shellfish_ref_there_nikar", ["yinya", "nikar", "yinyay"], EVIDENCE["nikar"]),
    row(28, "That prawn is there.", "Yinya wakal yinyay.", "yinya wakal yinyay | that prawn there", "r223_that_shellfish_ref_there_wakal", ["yinya", "wakal", "yinyay"], EVIDENCE["wakal"]),
    row(29, "That soldier crab is there.", "Yinya wuli-wuli yinyay.", "yinya wuli-wuli yinyay | that soldier.crab there", "r223_that_shellfish_ref_there_wuli_wuli", ["yinya", "wuli-wuli", "yinyay"], EVIDENCE["wuli-wuli"]),
    row(30, "That shellfish is there.", "Yinya wurrul yinyay.", "yinya wurrul yinyay | that shellfish there", "r223_that_shellfish_ref_there_wurrul", ["yinya", "wurrul", "yinyay"], EVIDENCE["wurrul"]),
    row(31, "That mudcrab is there.", "Kiju yinya yinyay.", "kiju yinya yinyay | that mudcrab there", "r223_shellfish_that_there_kiju", ["kiju", "yinya", "yinyay"], EVIDENCE["kiju"]),
    row(32, "That trocus shell is there.", "Dakaldakal yinya yinyay.", "dakaldakal yinya yinyay | that trocus.shell there", "r223_shellfish_that_there_dakaldakal", ["dakaldakal", "yinya", "yinyay"], EVIDENCE["dakaldakal"]),
    row(33, "That clam shell is there.", "Kajarrbi yinya yinyay.", "kajarrbi yinya yinyay | that clam.shell there", "r223_shellfish_that_there_kajarrbi", ["kajarrbi", "yinya", "yinyay"], EVIDENCE["kajarrbi"]),
    row(34, "That periwinkle is there.", "Kunkun yinya yinyay.", "kunkun yinya yinyay | that periwinkle there", "r223_shellfish_that_there_kunkun", ["kunkun", "yinya", "yinyay"], EVIDENCE["kunkun"]),
    row(35, "That octopus is there.", "Kurrija yinya yinyay.", "kurrija yinya yinyay | that octopus there", "r223_shellfish_that_there_kurrija", ["kurrija", "yinya", "yinyay"], EVIDENCE["kurrija"]),
    row(36, "That crayfish is there.", "Ngajay yinya yinyay.", "ngajay yinya yinyay | that crayfish there", "r223_shellfish_that_there_ngajay", ["ngajay", "yinya", "yinyay"], EVIDENCE["ngajay"]),
    row(37, "That oyster is there.", "Nikar yinya yinyay.", "nikar yinya yinyay | that oyster there", "r223_shellfish_that_there_nikar", ["nikar", "yinya", "yinyay"], EVIDENCE["nikar"]),
    row(38, "That prawn is there.", "Wakal yinya yinyay.", "wakal yinya yinyay | that prawn there", "r223_shellfish_that_there_wakal", ["wakal", "yinya", "yinyay"], EVIDENCE["wakal"]),
    row(39, "That soldier crab is there.", "Wuli-wuli yinya yinyay.", "wuli-wuli yinya yinyay | that soldier.crab there", "r223_shellfish_that_there_wuli_wuli", ["wuli-wuli", "yinya", "yinyay"], EVIDENCE["wuli-wuli"]),
    row(40, "That shellfish is there.", "Wurrul yinya yinyay.", "wurrul yinya yinyay | that shellfish there", "r223_shellfish_that_there_wurrul", ["wurrul", "yinya", "yinyay"], EVIDENCE["wurrul"]),
    row(41, "That mudcrab is here.", "Yinya kiju yaluy.", "yinya kiju yaluy | that mudcrab here", "r223_that_shellfish_ref_here_kiju", ["yinya", "kiju", "yaluy"], EVIDENCE["kiju"]),
    row(42, "That trocus shell is here.", "Yinya dakaldakal yaluy.", "yinya dakaldakal yaluy | that trocus.shell here", "r223_that_shellfish_ref_here_dakaldakal", ["yinya", "dakaldakal", "yaluy"], EVIDENCE["dakaldakal"]),
    row(43, "That clam shell is here.", "Yinya kajarrbi yaluy.", "yinya kajarrbi yaluy | that clam.shell here", "r223_that_shellfish_ref_here_kajarrbi", ["yinya", "kajarrbi", "yaluy"], EVIDENCE["kajarrbi"]),
    row(44, "That periwinkle is here.", "Yinya kunkun yaluy.", "yinya kunkun yaluy | that periwinkle here", "r223_that_shellfish_ref_here_kunkun", ["yinya", "kunkun", "yaluy"], EVIDENCE["kunkun"]),
    row(45, "That octopus is here.", "Yinya kurrija yaluy.", "yinya kurrija yaluy | that octopus here", "r223_that_shellfish_ref_here_kurrija", ["yinya", "kurrija", "yaluy"], EVIDENCE["kurrija"]),
    row(46, "That crayfish is here.", "Yinya ngajay yaluy.", "yinya ngajay yaluy | that crayfish here", "r223_that_shellfish_ref_here_ngajay", ["yinya", "ngajay", "yaluy"], EVIDENCE["ngajay"]),
    row(47, "That oyster is here.", "Yinya nikar yaluy.", "yinya nikar yaluy | that oyster here", "r223_that_shellfish_ref_here_nikar", ["yinya", "nikar", "yaluy"], EVIDENCE["nikar"]),
    row(48, "That prawn is here.", "Yinya wakal yaluy.", "yinya wakal yaluy | that prawn here", "r223_that_shellfish_ref_here_wakal", ["yinya", "wakal", "yaluy"], EVIDENCE["wakal"]),
    row(49, "That soldier crab is here.", "Yinya wuli-wuli yaluy.", "yinya wuli-wuli yaluy | that soldier.crab here", "r223_that_shellfish_ref_here_wuli_wuli", ["yinya", "wuli-wuli", "yaluy"], EVIDENCE["wuli-wuli"]),
    row(50, "That shellfish is here.", "Yinya wurrul yaluy.", "yinya wurrul yaluy | that shellfish here", "r223_that_shellfish_ref_here_wurrul", ["yinya", "wurrul", "yaluy"], EVIDENCE["wurrul"]),
]


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.strip())}\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("r223_"):
            issues.append(f"{label}: Rule 223 frame must start with r223_")
        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 223")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied carry-forward 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 223 target noun, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            dotted = selected.replace("-", ".").replace(" ", ".")
            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 and dotted 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 1 <= seq <= 10 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.") or len(low.split()) != 2):
            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.") or len(low.split()) != 2):
            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.") or len(low.split()) != 3):
            issues.append(f"{label}: rows 21-30 require Yinya TARGET yinyay")
        if 31 <= seq <= 40 and (not has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.") or len(low.split()) != 3 or low.startswith("yinya ")):
            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.") or len(low.split()) != 3):
            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 shellfish/crustacean use/habitat/event/polysemy 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,))
    else:
        db.execute(
            "INSERT INTO batches(label, cheatsheet_version, guide_version, notes, created_at) VALUES(?,?,?,?,?)",
            (LABEL, "Rule 223 draft", "operator-guide-2026-07-08", "draft under review", NOW),
        )
        batch_id = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()[0]

    collisions: list[str] = []
    for seq, _english, kuku, *_rest in ROWS:
        found = db.execute(
            """
            SELECT b.label, s.seq, s.status
            FROM sentences s JOIN batches b ON b.id=s.batch_id
            WHERE lower(s.kuku)=lower(?) AND s.status IN ('accepted','revised','under_review')
            """,
            (kuku,),
        ).fetchall()
        if found:
            collisions.append(f"{seq:02d} {kuku}: {found}")
    if collisions:
        raise SystemExit("duplicate preflight failed:\n" + "\n".join(collisions))

    record_event(
        db,
        batch_label=LABEL,
        phase="source",
        event_type="source-pass",
        actor="claude-main",
        detail="Checked Patz section 3.1 noun/fauna basis, Patz section 3.7 yinya/yaluy/yinyay support, earlier Rule 213 shellfish rows, and dictionary entries for kiju, dakaldakal, kajarrbi, kunkun, kurrija, ngajay, nikar, wakal, wuli-wuli, and wurrul. Replaced lint-failing jirrum after whole-corpus guard review. Admitted only selected bare shellfish/crustacean-reference labels.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="candidate-rejection",
        actor="claude-main",
        detail="Selected a second shellfish/crustacean-reference field after excluding earlier Rule 213 exact target heads, edible/fry/bait/cooking-heavy entries, fish/ray drift, habitat/place/source-prose entries, homograph/plant/weapon/stingray-barb/body-part entries, and all use/event/source-prose 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 over all 50 planned Rule 223 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        artifact_path="batch_scripts/bank_265.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="bank_265.py static guards passed: 50 explicit hand-authored rows, exactly one shellfish/crustacean-reference target noun per row, no loans, no target morphology, no shellfish/crustacean use/habitat/event/polysemy English, and only the five sourced deictic frame bands.",
        artifact_path="batch_scripts/bank_265.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, "under_review", confidence, NOW, NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

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


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