#!/usr/bin/env python3
"""Bank batch-260: Rule 218 third fish-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-260"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-260-third-fish-reference-lexical-expansion-after-rule217-process.md"

TARGET_HEADS = {
    "baban": "angelfish",
    "bububay": "black tip shark",
    "ngalkun": "mullet",
    "walkan": "diamond fish",
    "barrbal": "black bream",
    "jalkay": "salmon",
    "janbal": "blue spotted fantail ray",
    "jijirr": "red bream",
    "kurrubal": "cod",
    "murraja": "stonefish",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "ngayu", "nyulu", "yundu", "jana", "ngana", "nganya", "yununy", "nyunguny",
    "ngayku", "nyungu", "nyunba", "janangan", "nyaji", "nyajin", "nyajil",
    "kuyu", "bana", "jalun", "dukurr", "karangkal", "wawubaja", "ngandal",
    "badur", "makarr", "kalka", "damal", "karrbal", "nukal", "nuka", "dungay",
    "kaday", "wunay", "wukurril", "jurrkil", "bakal", "bakanyji", "kuli", "badi",
    "badibu", "bilaji", "bunjulu", "jilngu", "karrulji", "kilkirr", "midir",
    "ngarmu", "yalnganji", "yubuji", "milkaji", "dalkal", "dandarrbina", "dawal",
    "jarbir", "jukar-jukarbina", "julba", "julmba", "kudi", "kundur-kundur",
    "danbal", "bayil", "bayilbayil", "yaba", "yawu", "yidi", "yidilnyul", "murrabal",
    "kalngkan", "kurriyala", "yaburr", "kanyaji", "mujarrka",
}
DENY_ENGLISH = (
    "catch", "caught", "catching", "net", "line", "hook", "spear", "speared", "spearing",
    "eat", "eating", "edible", "cook", "cooked", "cooking", "food", "bait", "taboo",
    "old people", "storm", "thunder", "rainstorm", "rainstorms", "story", "story-site",
    "river", "sea", "reef", "mangrove", "mangroves", "habitat", "swim", "swimming",
    "school", "bite", "biting", "danger", "poison", "injury", "poked", "stone",
    "tree", "quondong", "colour", "color", "devil", "dialect", "equivalent", "freshwater prose",
)


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")


ROWS = [
    row(1, "The angelfish is here.", "Baban yaluy.", "baban yaluy | angelfish here", "r218_fish_ref_here_baban", ["baban", "yaluy"], "Dictionary baban noun 'angelfish'; parallel anglefish spelling treated as source variant only. Patz section 3.1 nouns include fauna; section 3.7 yaluy 'here'."),
    row(2, "The black tip shark is here.", "Bububay yaluy.", "bububay yaluy | black.tip.shark here", "r218_fish_ref_here_bububay", ["bububay", "yaluy"], "Dictionary bububay noun 'black tip shark'; empty duplicate source entry ignored. Patz section 3.7 yaluy."),
    row(3, "The mullet is here.", "Ngalkun yaluy.", "ngalkun yaluy | mullet here", "r218_fish_ref_here_ngalkun", ["ngalkun", "yaluy"], "Dictionary ngalkun noun 'mullet'; selected after kijukum failed phonotactic lint. Patz section 3.7 yaluy."),
    row(4, "The diamond fish is here.", "Walkan yaluy.", "walkan yaluy | diamond.fish here", "r218_fish_ref_here_walkan", ["walkan", "yaluy"], "Dictionary walkan noun 'diamond fish'; devil-ray alternate kept closed. Patz section 3.7 yaluy."),
    row(5, "The black bream is here.", "Barrbal yaluy.", "barrbal yaluy | black.bream here", "r218_fish_ref_here_barrbal", ["barrbal", "yaluy"], "Dictionary barrbal noun 'black bream'; colour-predicate import closed. Patz section 3.7 yaluy."),
    row(6, "The salmon is here.", "Jalkay yaluy.", "jalkay yaluy | salmon here", "r218_fish_ref_here_jalkay", ["jalkay", "yaluy"], "Dictionary jalkay noun 'salmon'; Patz section 3.7 yaluy."),
    row(7, "The blue spotted fantail ray is here.", "Janbal yaluy.", "janbal yaluy | blue.spotted.fantail.ray here", "r218_fish_ref_here_janbal", ["janbal", "yaluy"], "Dictionary janbal noun 'blue spotted fantail ray'; quondong/tree homograph closed. Patz section 3.7 yaluy."),
    row(8, "The red bream is here.", "Jijirr yaluy.", "jijirr yaluy | red.bream here", "r218_fish_ref_here_jijirr", ["jijirr", "yaluy"], "Dictionary jijirr noun 'red bream'; colour-predicate import closed. Patz section 3.7 yaluy."),
    row(9, "The cod is here.", "Kurrubal yaluy.", "kurrubal yaluy | cod here", "r218_fish_ref_here_kurrubal", ["kurrubal", "yaluy"], "Dictionary kurrubal noun 'fresh water cod'; production label narrowed to cod. Patz section 3.7 yaluy."),
    row(10, "The stonefish is here.", "Murraja yaluy.", "murraja yaluy | stonefish here", "r218_fish_ref_here_murraja", ["murraja", "yaluy"], "Dictionary murraja noun 'stonefish'; injury/poking event prose closed. Patz section 3.7 yaluy."),
    row(11, "The angelfish is there.", "Baban yinyay.", "baban yinyay | angelfish there", "r218_fish_ref_there_baban", ["baban", "yinyay"], "Dictionary baban noun 'angelfish'; Patz section 3.7 yinyay 'there'."),
    row(12, "The black tip shark is there.", "Bububay yinyay.", "bububay yinyay | black.tip.shark there", "r218_fish_ref_there_bububay", ["bububay", "yinyay"], "Dictionary bububay noun 'black tip shark'; Patz section 3.7 yinyay."),
    row(13, "The mullet is there.", "Ngalkun yinyay.", "ngalkun yinyay | mullet there", "r218_fish_ref_there_ngalkun", ["ngalkun", "yinyay"], "Dictionary ngalkun noun 'mullet'; Patz section 3.7 yinyay."),
    row(14, "The diamond fish is there.", "Walkan yinyay.", "walkan yinyay | diamond.fish there", "r218_fish_ref_there_walkan", ["walkan", "yinyay"], "Dictionary walkan noun 'diamond fish'; Patz section 3.7 yinyay."),
    row(15, "The black bream is there.", "Barrbal yinyay.", "barrbal yinyay | black.bream there", "r218_fish_ref_there_barrbal", ["barrbal", "yinyay"], "Dictionary barrbal noun 'black bream'; Patz section 3.7 yinyay."),
    row(16, "The salmon is there.", "Jalkay yinyay.", "jalkay yinyay | salmon there", "r218_fish_ref_there_jalkay", ["jalkay", "yinyay"], "Dictionary jalkay noun 'salmon'; Patz section 3.7 yinyay."),
    row(17, "The blue spotted fantail ray is there.", "Janbal yinyay.", "janbal yinyay | blue.spotted.fantail.ray there", "r218_fish_ref_there_janbal", ["janbal", "yinyay"], "Dictionary janbal noun 'blue spotted fantail ray'; Patz section 3.7 yinyay."),
    row(18, "The red bream is there.", "Jijirr yinyay.", "jijirr yinyay | red.bream there", "r218_fish_ref_there_jijirr", ["jijirr", "yinyay"], "Dictionary jijirr noun 'red bream'; Patz section 3.7 yinyay."),
    row(19, "The cod is there.", "Kurrubal yinyay.", "kurrubal yinyay | cod there", "r218_fish_ref_there_kurrubal", ["kurrubal", "yinyay"], "Dictionary kurrubal noun 'cod'; Patz section 3.7 yinyay."),
    row(20, "The stonefish is there.", "Murraja yinyay.", "murraja yinyay | stonefish there", "r218_fish_ref_there_murraja", ["murraja", "yinyay"], "Dictionary murraja noun 'stonefish'; Patz section 3.7 yinyay."),
    row(21, "That angelfish is there.", "Yinya baban yinyay.", "yinya baban yinyay | that angelfish there", "r218_that_fish_ref_there_baban", ["yinya", "baban", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dictionary baban noun 'angelfish'."),
    row(22, "That black tip shark is there.", "Yinya bububay yinyay.", "yinya bububay yinyay | that black.tip.shark there", "r218_that_fish_ref_there_bububay", ["yinya", "bububay", "yinyay"], "Patz section 3.7 yinya with noun; dictionary bububay noun 'black tip shark'."),
    row(23, "That mullet is there.", "Yinya ngalkun yinyay.", "yinya ngalkun yinyay | that mullet there", "r218_that_fish_ref_there_ngalkun", ["yinya", "ngalkun", "yinyay"], "Patz section 3.7 yinya with noun; dictionary ngalkun noun 'mullet'."),
    row(24, "That diamond fish is there.", "Yinya walkan yinyay.", "yinya walkan yinyay | that diamond.fish there", "r218_that_fish_ref_there_walkan", ["yinya", "walkan", "yinyay"], "Patz section 3.7 yinya with noun; dictionary walkan noun 'diamond fish'."),
    row(25, "That black bream is there.", "Yinya barrbal yinyay.", "yinya barrbal yinyay | that black.bream there", "r218_that_fish_ref_there_barrbal", ["yinya", "barrbal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary barrbal noun 'black bream'."),
    row(26, "That salmon is there.", "Yinya jalkay yinyay.", "yinya jalkay yinyay | that salmon there", "r218_that_fish_ref_there_jalkay", ["yinya", "jalkay", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jalkay noun 'salmon'."),
    row(27, "That blue spotted fantail ray is there.", "Yinya janbal yinyay.", "yinya janbal yinyay | that blue.spotted.fantail.ray there", "r218_that_fish_ref_there_janbal", ["yinya", "janbal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary janbal noun 'blue spotted fantail ray'."),
    row(28, "That red bream is there.", "Yinya jijirr yinyay.", "yinya jijirr yinyay | that red.bream there", "r218_that_fish_ref_there_jijirr", ["yinya", "jijirr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jijirr noun 'red bream'."),
    row(29, "That cod is there.", "Yinya kurrubal yinyay.", "yinya kurrubal yinyay | that cod there", "r218_that_fish_ref_there_kurrubal", ["yinya", "kurrubal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kurrubal noun 'cod'."),
    row(30, "That stonefish is there.", "Yinya murraja yinyay.", "yinya murraja yinyay | that stonefish there", "r218_that_fish_ref_there_murraja", ["yinya", "murraja", "yinyay"], "Patz section 3.7 yinya with noun; dictionary murraja noun 'stonefish'."),
    row(31, "That angelfish is there.", "Baban yinya yinyay.", "baban yinya yinyay | that angelfish there", "r218_fish_that_there_baban", ["baban", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary baban noun 'angelfish'."),
    row(32, "That black tip shark is there.", "Bububay yinya yinyay.", "bububay yinya yinyay | that black.tip.shark there", "r218_fish_that_there_bububay", ["bububay", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bububay noun 'black tip shark'."),
    row(33, "That mullet is there.", "Ngalkun yinya yinyay.", "ngalkun yinya yinyay | that mullet there", "r218_fish_that_there_ngalkun", ["ngalkun", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary ngalkun noun 'mullet'."),
    row(34, "That diamond fish is there.", "Walkan yinya yinyay.", "walkan yinya yinyay | that diamond.fish there", "r218_fish_that_there_walkan", ["walkan", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary walkan noun 'diamond fish'."),
    row(35, "That black bream is there.", "Barrbal yinya yinyay.", "barrbal yinya yinyay | that black.bream there", "r218_fish_that_there_barrbal", ["barrbal", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary barrbal noun 'black bream'."),
    row(36, "That salmon is there.", "Jalkay yinya yinyay.", "jalkay yinya yinyay | that salmon there", "r218_fish_that_there_jalkay", ["jalkay", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jalkay noun 'salmon'."),
    row(37, "That blue spotted fantail ray is there.", "Janbal yinya yinyay.", "janbal yinya yinyay | that blue.spotted.fantail.ray there", "r218_fish_that_there_janbal", ["janbal", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary janbal noun 'blue spotted fantail ray'."),
    row(38, "That red bream is there.", "Jijirr yinya yinyay.", "jijirr yinya yinyay | that red.bream there", "r218_fish_that_there_jijirr", ["jijirr", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jijirr noun 'red bream'."),
    row(39, "That cod is there.", "Kurrubal yinya yinyay.", "kurrubal yinya yinyay | that cod there", "r218_fish_that_there_kurrubal", ["kurrubal", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary kurrubal noun 'cod'."),
    row(40, "That stonefish is there.", "Murraja yinya yinyay.", "murraja yinya yinyay | that stonefish there", "r218_fish_that_there_murraja", ["murraja", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary murraja noun 'stonefish'."),
    row(41, "That angelfish is here.", "Yinya baban yaluy.", "yinya baban yaluy | that angelfish here", "r218_that_fish_ref_here_baban", ["yinya", "baban", "yaluy"], "Patz section 3.7 yinya with noun; dictionary baban noun 'angelfish'; yaluy 'here'."),
    row(42, "That black tip shark is here.", "Yinya bububay yaluy.", "yinya bububay yaluy | that black.tip.shark here", "r218_that_fish_ref_here_bububay", ["yinya", "bububay", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bububay noun 'black tip shark'."),
    row(43, "That mullet is here.", "Yinya ngalkun yaluy.", "yinya ngalkun yaluy | that mullet here", "r218_that_fish_ref_here_ngalkun", ["yinya", "ngalkun", "yaluy"], "Patz section 3.7 yinya with noun; dictionary ngalkun noun 'mullet'."),
    row(44, "That diamond fish is here.", "Yinya walkan yaluy.", "yinya walkan yaluy | that diamond.fish here", "r218_that_fish_ref_here_walkan", ["yinya", "walkan", "yaluy"], "Patz section 3.7 yinya with noun; dictionary walkan noun 'diamond fish'."),
    row(45, "That black bream is here.", "Yinya barrbal yaluy.", "yinya barrbal yaluy | that black.bream here", "r218_that_fish_ref_here_barrbal", ["yinya", "barrbal", "yaluy"], "Patz section 3.7 yinya with noun; dictionary barrbal noun 'black bream'."),
    row(46, "That salmon is here.", "Yinya jalkay yaluy.", "yinya jalkay yaluy | that salmon here", "r218_that_fish_ref_here_jalkay", ["yinya", "jalkay", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jalkay noun 'salmon'."),
    row(47, "That blue spotted fantail ray is here.", "Yinya janbal yaluy.", "yinya janbal yaluy | that blue.spotted.fantail.ray here", "r218_that_fish_ref_here_janbal", ["yinya", "janbal", "yaluy"], "Patz section 3.7 yinya with noun; dictionary janbal noun 'blue spotted fantail ray'."),
    row(48, "That red bream is here.", "Yinya jijirr yaluy.", "yinya jijirr yaluy | that red.bream here", "r218_that_fish_ref_here_jijirr", ["yinya", "jijirr", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jijirr noun 'red bream'."),
    row(49, "That cod is here.", "Yinya kurrubal yaluy.", "yinya kurrubal yaluy | that cod here", "r218_that_fish_ref_here_kurrubal", ["yinya", "kurrubal", "yaluy"], "Patz section 3.7 yinya with noun; dictionary kurrubal noun 'cod'."),
    row(50, "That stonefish is here.", "Yinya murraja yaluy.", "yinya murraja yaluy | that stonefish here", "r218_that_fish_ref_here_murraja", ["yinya", "murraja", "yaluy"], "Patz section 3.7 yinya with noun; dictionary murraja noun 'stonefish'."),
]


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("r218_"):
            issues.append(f"{label}: Rule 218 frame must start with r218_")
        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 218")
        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 218 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 fish-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,))
        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 218 draft: third fish-reference lexical expansion after Rule 217",
                "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

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

    verified_before, words_before = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    under_review = db.execute(
        "SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='under_review'",
        (batch_id,),
    ).fetchone()[0]

    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, and dictionary entries "
            "for baban, bububay, ngalkun, walkan, barrbal, jalkay, janbal, jijirr, kurrubal, and murraja. "
            "Admitted only selected bare fish-reference species 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 third fish-reference field only after excluding dialect-only, food-taboo, story-site, habitat-heavy, use-event, generic-fish, "
            "productive-reduplication, illegal-coda, and strong-polysemy entries. Replaced kijukum after lint and kept prior fish-reference targets and high-pressure candidates closed."
        ),
        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 218 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="python3 batch_scripts/bank_260.py cross-corpus duplicate scan",
        artifact_path="batch_scripts/bank_260.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail=(
            "bank_260.py static guards passed: 50 explicit hand-authored rows, exactly one fish-reference target noun per row, "
            "no loans, no target morphology, no fish-use/habitat/event/polysemy English, and only the five sourced deictic frame bands."
        ),
        artifact_path="batch_scripts/bank_260.py",
        created_at=NOW,
    )
    db.commit()
    print(
        f"banked {LABEL}: rows={len(ROWS)}, under_review={under_review}, "
        f"verified_before_close={verified_before}, words_before={words_before or 0}"
    )
    return 0


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