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

TARGET_HEADS = {
    "bajuy": "lizard",
    "bilngkumu": "crocodile",
    "binanjal": "frill necked lizard",
    "bindimu": "black snake",
    "bubal": "tree snake",
    "jijirrbay": "whip snake",
    "kabul": "rock python",
    "kalajarr": "scrub goanna",
    "kundurr": "death adder",
    "yuday": "frog",
}
SUPPORT = {"yinya", "yaluy", "yinyay"}
DENY_KUKU = {
    "banamu", "binju", "dukul-mukul", "jirabay", "junbirr", "kabuljaka",
    "kulmba-kulmba", "kurriyala", "ngawurr-ngawun", "ngumbul", "biwul",
    "bajabaja", "bajalji", "barka", "bilbil-bilbil", "jadi", "jalbil",
    "jarba", "jimalili", "jinkalmu", "kalkamuku", "karrkurr", "kungkun",
    "kurmba-kurmba", "ngawiya", "ngujay", "walkarr", "yalnga", "yirku-yirku",
    "yuray", "bala", "darrba", "jarrabina", "jayju", "jungarr", "kukur",
    "mali", "murramu", "ngumbi", "yawa", "baban", "bububay", "ngalkun",
    "walkan", "barrbal", "jalkay", "janbal", "jijirr", "kurrubal", "murraja",
}
DENY_ENGLISH = (
    "hunt", "hunting", "hunter", "catch", "caught", "catching", "trap", "trapped",
    "kill", "killed", "bite", "biting", "poison", "poisonous", "venom", "danger",
    "dangerous", "fear", "frighten", "frightened", "harmless", "food", "edible",
    "eat", "eating", "ate", "meat", "cook", "cooked", "egg", "eggs", "skin",
    "scale", "body-part", "habitat", "ecology", "water", "river", "sea", "swamp",
    "story", "story-site", "myth", "legend", "mythological", "place", "place-name",
    "firestick", "fighter", "bald", "hat", "chase", "chased", "split", "island",
    "tree-climbing", "climb", "domestic", "loan", "introduced", "mother-in-law",
    "avoidance", "support inflection", "plural", "many",
)


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 lizard is here.", "Bajuy yaluy.", "bajuy yaluy | lizard here", "r220_reptile_ref_here_bajuy", ["bajuy", "yaluy"], "Dictionary bajuy noun 'lizard' from definition 'slippery lizard'. Patz section 3.1 nouns include fauna; section 3.7 yaluy 'here'."),
    row(2, "The crocodile is here.", "Bilngkumu yaluy.", "bilngkumu yaluy | crocodile here", "r220_reptile_ref_here_bilngkumu", ["bilngkumu", "yaluy"], "Dictionary bilngkumu noun 'crocodile' with salt-water-crocodile definition; water/habitat/danger prose fenced off. Patz section 3.7 yaluy."),
    row(3, "The frill necked lizard is here.", "Binanjal yaluy.", "binanjal yaluy | frill.necked.lizard here", "r220_reptile_ref_here_binanjal", ["binanjal", "yaluy"], "Dictionary binanjal noun 'frill necked lizard'; neck/body display event prose fenced off. Patz section 3.7 yaluy."),
    row(4, "The black snake is here.", "Bindimu yaluy.", "bindimu yaluy | black.snake here", "r220_reptile_ref_here_bindimu", ["bindimu", "yaluy"], "Dictionary bindimu noun 'black snake'; red-bellied-black-snake duplicate sense and colour predicate fenced off. Patz section 3.7 yaluy."),
    row(5, "The tree snake is here.", "Bubal yaluy.", "bubal yaluy | tree.snake here", "r220_reptile_ref_here_bubal", ["bubal", "yaluy"], "Dictionary bubal noun 'tree snake'; tree/habitat and biting event prose fenced off. Patz section 3.7 yaluy."),
    row(6, "The whip snake is here.", "Jijirrbay yaluy.", "jijirrbay yaluy | whip.snake here", "r220_reptile_ref_here_jijirrbay", ["jijirrbay", "yaluy"], "Dictionary jijirrbay noun 'whip snake'; whip/object and bite prose fenced off. Patz section 3.7 yaluy."),
    row(7, "The rock python is here.", "Kabul yaluy.", "kabul yaluy | rock.python here", "r220_reptile_ref_here_kabul", ["kabul", "yaluy"], "Dictionary kabul noun 'rock python'; rock/place, food, and squeezing-event prose fenced off. Patz section 3.7 yaluy."),
    row(8, "The scrub goanna is here.", "Kalajarr yaluy.", "kalajarr yaluy | scrub.goanna here", "r220_reptile_ref_here_kalajarr", ["kalajarr", "yaluy"], "Dictionary kalajarr noun 'scrub goanna'; scrub/habitat, climbing, food, and cooking prose fenced off. Patz section 3.7 yaluy."),
    row(9, "The death adder is here.", "Kundurr yaluy.", "kundurr yaluy | death.adder here", "r220_reptile_ref_here_kundurr", ["kundurr", "yaluy"], "Dictionary kundurr noun 'death adder'; danger/biting/poison prose fenced off. Patz section 3.7 yaluy."),
    row(10, "The frog is here.", "Yuday yaluy.", "yuday yaluy | frog here", "r220_reptile_ref_here_yuday", ["yuday", "yaluy"], "Dictionary yuday noun 'frog'; edible/rain/singing/swamp event prose fenced off. Patz section 3.7 yaluy."),
    row(11, "The lizard is there.", "Bajuy yinyay.", "bajuy yinyay | lizard there", "r220_reptile_ref_there_bajuy", ["bajuy", "yinyay"], "Dictionary bajuy noun 'lizard'; Patz section 3.7 yinyay 'there'."),
    row(12, "The crocodile is there.", "Bilngkumu yinyay.", "bilngkumu yinyay | crocodile there", "r220_reptile_ref_there_bilngkumu", ["bilngkumu", "yinyay"], "Dictionary bilngkumu noun 'crocodile'; Patz section 3.7 yinyay."),
    row(13, "The frill necked lizard is there.", "Binanjal yinyay.", "binanjal yinyay | frill.necked.lizard there", "r220_reptile_ref_there_binanjal", ["binanjal", "yinyay"], "Dictionary binanjal noun 'frill necked lizard'; Patz section 3.7 yinyay."),
    row(14, "The black snake is there.", "Bindimu yinyay.", "bindimu yinyay | black.snake there", "r220_reptile_ref_there_bindimu", ["bindimu", "yinyay"], "Dictionary bindimu noun 'black snake'; Patz section 3.7 yinyay."),
    row(15, "The tree snake is there.", "Bubal yinyay.", "bubal yinyay | tree.snake there", "r220_reptile_ref_there_bubal", ["bubal", "yinyay"], "Dictionary bubal noun 'tree snake'; Patz section 3.7 yinyay."),
    row(16, "The whip snake is there.", "Jijirrbay yinyay.", "jijirrbay yinyay | whip.snake there", "r220_reptile_ref_there_jijirrbay", ["jijirrbay", "yinyay"], "Dictionary jijirrbay noun 'whip snake'; Patz section 3.7 yinyay."),
    row(17, "The rock python is there.", "Kabul yinyay.", "kabul yinyay | rock.python there", "r220_reptile_ref_there_kabul", ["kabul", "yinyay"], "Dictionary kabul noun 'rock python'; Patz section 3.7 yinyay."),
    row(18, "The scrub goanna is there.", "Kalajarr yinyay.", "kalajarr yinyay | scrub.goanna there", "r220_reptile_ref_there_kalajarr", ["kalajarr", "yinyay"], "Dictionary kalajarr noun 'scrub goanna'; Patz section 3.7 yinyay."),
    row(19, "The death adder is there.", "Kundurr yinyay.", "kundurr yinyay | death.adder there", "r220_reptile_ref_there_kundurr", ["kundurr", "yinyay"], "Dictionary kundurr noun 'death adder'; Patz section 3.7 yinyay."),
    row(20, "The frog is there.", "Yuday yinyay.", "yuday yinyay | frog there", "r220_reptile_ref_there_yuday", ["yuday", "yinyay"], "Dictionary yuday noun 'frog'; Patz section 3.7 yinyay."),
    row(21, "That lizard is there.", "Yinya bajuy yinyay.", "yinya bajuy yinyay | that lizard there", "r220_that_reptile_ref_there_bajuy", ["yinya", "bajuy", "yinyay"], "Patz section 3.7 yinya can co-occur with a noun; dictionary bajuy noun 'lizard'."),
    row(22, "That crocodile is there.", "Yinya bilngkumu yinyay.", "yinya bilngkumu yinyay | that crocodile there", "r220_that_reptile_ref_there_bilngkumu", ["yinya", "bilngkumu", "yinyay"], "Patz section 3.7 yinya with noun; dictionary bilngkumu noun 'crocodile'."),
    row(23, "That frill necked lizard is there.", "Yinya binanjal yinyay.", "yinya binanjal yinyay | that frill.necked.lizard there", "r220_that_reptile_ref_there_binanjal", ["yinya", "binanjal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary binanjal noun 'frill necked lizard'."),
    row(24, "That black snake is there.", "Yinya bindimu yinyay.", "yinya bindimu yinyay | that black.snake there", "r220_that_reptile_ref_there_bindimu", ["yinya", "bindimu", "yinyay"], "Patz section 3.7 yinya with noun; dictionary bindimu noun 'black snake'."),
    row(25, "That tree snake is there.", "Yinya bubal yinyay.", "yinya bubal yinyay | that tree.snake there", "r220_that_reptile_ref_there_bubal", ["yinya", "bubal", "yinyay"], "Patz section 3.7 yinya with noun; dictionary bubal noun 'tree snake'."),
    row(26, "That whip snake is there.", "Yinya jijirrbay yinyay.", "yinya jijirrbay yinyay | that whip.snake there", "r220_that_reptile_ref_there_jijirrbay", ["yinya", "jijirrbay", "yinyay"], "Patz section 3.7 yinya with noun; dictionary jijirrbay noun 'whip snake'."),
    row(27, "That rock python is there.", "Yinya kabul yinyay.", "yinya kabul yinyay | that rock.python there", "r220_that_reptile_ref_there_kabul", ["yinya", "kabul", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kabul noun 'rock python'."),
    row(28, "That scrub goanna is there.", "Yinya kalajarr yinyay.", "yinya kalajarr yinyay | that scrub.goanna there", "r220_that_reptile_ref_there_kalajarr", ["yinya", "kalajarr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kalajarr noun 'scrub goanna'."),
    row(29, "That death adder is there.", "Yinya kundurr yinyay.", "yinya kundurr yinyay | that death.adder there", "r220_that_reptile_ref_there_kundurr", ["yinya", "kundurr", "yinyay"], "Patz section 3.7 yinya with noun; dictionary kundurr noun 'death adder'."),
    row(30, "That frog is there.", "Yinya yuday yinyay.", "yinya yuday yinyay | that frog there", "r220_that_reptile_ref_there_yuday", ["yinya", "yuday", "yinyay"], "Patz section 3.7 yinya with noun; dictionary yuday noun 'frog'."),
    row(31, "That lizard is there.", "Bajuy yinya yinyay.", "bajuy yinya yinyay | that lizard there", "r220_reptile_that_there_bajuy", ["bajuy", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bajuy noun 'lizard'."),
    row(32, "That crocodile is there.", "Bilngkumu yinya yinyay.", "bilngkumu yinya yinyay | that crocodile there", "r220_reptile_that_there_bilngkumu", ["bilngkumu", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bilngkumu noun 'crocodile'."),
    row(33, "That frill necked lizard is there.", "Binanjal yinya yinyay.", "binanjal yinya yinyay | that frill.necked.lizard there", "r220_reptile_that_there_binanjal", ["binanjal", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary binanjal noun 'frill necked lizard'."),
    row(34, "That black snake is there.", "Bindimu yinya yinyay.", "bindimu yinya yinyay | that black.snake there", "r220_reptile_that_there_bindimu", ["bindimu", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bindimu noun 'black snake'."),
    row(35, "That tree snake is there.", "Bubal yinya yinyay.", "bubal yinya yinyay | that tree.snake there", "r220_reptile_that_there_bubal", ["bubal", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary bubal noun 'tree snake'."),
    row(36, "That whip snake is there.", "Jijirrbay yinya yinyay.", "jijirrbay yinya yinyay | that whip.snake there", "r220_reptile_that_there_jijirrbay", ["jijirrbay", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary jijirrbay noun 'whip snake'."),
    row(37, "That rock python is there.", "Kabul yinya yinyay.", "kabul yinya yinyay | that rock.python there", "r220_reptile_that_there_kabul", ["kabul", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary kabul noun 'rock python'."),
    row(38, "That scrub goanna is there.", "Kalajarr yinya yinyay.", "kalajarr yinya yinyay | that scrub.goanna there", "r220_reptile_that_there_kalajarr", ["kalajarr", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary kalajarr noun 'scrub goanna'."),
    row(39, "That death adder is there.", "Kundurr yinya yinyay.", "kundurr yinya yinyay | that death.adder there", "r220_reptile_that_there_kundurr", ["kundurr", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary kundurr noun 'death adder'."),
    row(40, "That frog is there.", "Yuday yinya yinyay.", "yuday yinya yinyay | that frog there", "r220_reptile_that_there_yuday", ["yuday", "yinya", "yinyay"], "Patz section 3.7 yinya can follow a noun; dictionary yuday noun 'frog'."),
    row(41, "That lizard is here.", "Yinya bajuy yaluy.", "yinya bajuy yaluy | that lizard here", "r220_that_reptile_ref_here_bajuy", ["yinya", "bajuy", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bajuy noun 'lizard'; yaluy 'here'."),
    row(42, "That crocodile is here.", "Yinya bilngkumu yaluy.", "yinya bilngkumu yaluy | that crocodile here", "r220_that_reptile_ref_here_bilngkumu", ["yinya", "bilngkumu", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bilngkumu noun 'crocodile'; yaluy 'here'."),
    row(43, "That frill necked lizard is here.", "Yinya binanjal yaluy.", "yinya binanjal yaluy | that frill.necked.lizard here", "r220_that_reptile_ref_here_binanjal", ["yinya", "binanjal", "yaluy"], "Patz section 3.7 yinya with noun; dictionary binanjal noun 'frill necked lizard'; yaluy 'here'."),
    row(44, "That black snake is here.", "Yinya bindimu yaluy.", "yinya bindimu yaluy | that black.snake here", "r220_that_reptile_ref_here_bindimu", ["yinya", "bindimu", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bindimu noun 'black snake'; yaluy 'here'."),
    row(45, "That tree snake is here.", "Yinya bubal yaluy.", "yinya bubal yaluy | that tree.snake here", "r220_that_reptile_ref_here_bubal", ["yinya", "bubal", "yaluy"], "Patz section 3.7 yinya with noun; dictionary bubal noun 'tree snake'; yaluy 'here'."),
    row(46, "That whip snake is here.", "Yinya jijirrbay yaluy.", "yinya jijirrbay yaluy | that whip.snake here", "r220_that_reptile_ref_here_jijirrbay", ["yinya", "jijirrbay", "yaluy"], "Patz section 3.7 yinya with noun; dictionary jijirrbay noun 'whip snake'; yaluy 'here'."),
    row(47, "That rock python is here.", "Yinya kabul yaluy.", "yinya kabul yaluy | that rock.python here", "r220_that_reptile_ref_here_kabul", ["yinya", "kabul", "yaluy"], "Patz section 3.7 yinya with noun; dictionary kabul noun 'rock python'; yaluy 'here'."),
    row(48, "That scrub goanna is here.", "Yinya kalajarr yaluy.", "yinya kalajarr yaluy | that scrub.goanna here", "r220_that_reptile_ref_here_kalajarr", ["yinya", "kalajarr", "yaluy"], "Patz section 3.7 yinya with noun; dictionary kalajarr noun 'scrub goanna'; yaluy 'here'."),
    row(49, "That death adder is here.", "Yinya kundurr yaluy.", "yinya kundurr yaluy | that death.adder here", "r220_that_reptile_ref_here_kundurr", ["yinya", "kundurr", "yaluy"], "Patz section 3.7 yinya with noun; dictionary kundurr noun 'death adder'; yaluy 'here'."),
    row(50, "That frog is here.", "Yinya yuday yaluy.", "yinya yuday yaluy | that frog here", "r220_that_reptile_ref_here_yuday", ["yinya", "yuday", "yaluy"], "Patz section 3.7 yinya with noun; dictionary yuday noun 'frog'; yaluy 'here'."),
]


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("r220_"):
            issues.append(f"{label}: Rule 220 frame must start with r220_")
        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 220")
        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 220 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 reptile/amphibian 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 220 draft: second reptile/amphibian-reference lexical expansion after Rule 219",
                "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, earlier Rule 175-176 reptile rows, "
            "and dictionary entries for bajuy, bilngkumu, binanjal, bindimu, bubal, jijirrbay, kabul, kalajarr, kundurr, and yuday. "
            "Admitted only selected bare reptile/amphibian-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 reptile/amphibian-reference field after excluding exact Rule 175-176 surfaces, biwul black-snake homograph because the corpus verifies biwul as mother-in-law, "
            "story-site/myth-heavy entries, poison/biting/food/event-heavy entries, productive reduplication pressure, water/habitat-heavy entries, and all source-prose event semantics."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="duplicate-preflight",
        actor="claude-main",
        detail="Exact duplicate preflight over all 50 planned Rule 220 Kuku surfaces returned no accepted, revised, or under-review collisions.",
        command="python3 batch_scripts/bank_262.py cross-corpus duplicate scan",
        artifact_path="batch_scripts/bank_262.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail=(
            "bank_262.py static guards passed: 50 explicit hand-authored rows, exactly one reptile/amphibian-reference target noun per row, no loans, "
            "no target morphology, no reptile/amphibian-use/habitat/event/polysemy English, and only the five sourced deictic frame bands."
        ),
        artifact_path="batch_scripts/bank_262.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())
