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

TARGET_HEADS = {
    "bikibiki": "pig",
    "kadar": "wallaby",
    "julmbanu": "grey.kangaroo",
    "kaya": "dog",
    "walkarr": "black.scrub.goanna",
    "jarba": "snake",
    "bajabaja": "blue-tongue.lizard",
}
SUPPORT_FORMS = {"madja-nga", "ngalkal-ba", "bayan-ba", "bubu-ngu"}
PRONOUN_A = {"ngayu", "ngana", "jana"}
COMMON_A = {"ngamu-ngku", "nganjan-angka", "babi-ngka", "karrkay-ngku", "kami-ngka", "jalbu-ngku", "dingkar-angka"}
DENY = {
    "biki", "bulki", "ngiwa", "kuni", "kunin", "bayka", "baykan", "nuka", "nukan", "balbi", "dama", "daman",
    "karrba", "karrban", "bijan", "wukurrin", "yirrka", "yirrkan", "minya", "mayi", "kalka", "marrkin",
    "dirra", "ngandal", "biji", "kuli-ji", "yinil", "yiril", "ngurrku",
}
DENIED_ENGLISH = (
    "hunt", "hunted", "hunting", "kill", "killed", "killing", "spear", "speared", "spearing", "shoot",
    "shot", "chase", "chased", "catch", "caught", "cut", "cutting", "bite", "bit", "biting", "lick",
    "licked", "bark", "barked", "eat", "ate", "eating", "meat", "food", "poison", "sick", "fear", "afraid",
    "taboo", "storm", "story", "myth", "totem", "track", "egg", "tail", "teeth", "tooth", "vicious",
)


def js(values: list[str]) -> str:
    return json.dumps(values, ensure_ascii=False)


def loan_for(words: list[str]) -> str:
    return js(["bikibiki"]) if "bikibiki" in words else js([])


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), loan_for(words), evidence, "0.84")


ROWS = [
    row(1, "The pig is big.", "Bikibiki yalbay.",
        "bikibiki yalbay | pig big", "r147_state_pig_big", ["bikibiki", "yalbay"], "Bikibiki pig loan/contact animal; yalbay big state predicate."),
    row(2, "The wallaby is big.", "Kadar yalbay.",
        "kadar yalbay | wallaby big", "r147_state_wallaby_big", ["kadar", "yalbay"], "Kadar plains wallaby/wallaby; yalbay big state predicate."),
    row(3, "The grey kangaroo is big.", "Julmbanu yalbay.",
        "julmbanu yalbay | grey.kangaroo big", "r147_state_grey_kangaroo_big", ["julmbanu", "yalbay"], "Julmbanu grey kangaroo; Patz example has julmbanu as big grey kangaroo."),
    row(4, "The dog is big.", "Kaya yalbay.",
        "kaya yalbay | dog big", "r147_state_dog_big", ["kaya", "yalbay"], "Patz text 51 has kaya yalbay dog big."),
    row(5, "The black scrub goanna is big.", "Walkarr yalbay.",
        "walkarr yalbay | black.scrub.goanna big", "r147_state_goanna_big", ["walkarr", "yalbay"], "Walkarr black scrub goanna; only name and size."),
    row(6, "The snake is big.", "Jarba yalbay.",
        "jarba yalbay | snake big", "r147_state_snake_big", ["jarba", "yalbay"], "Jarba generic snake only; no bite/fear/poison."),
    row(7, "The blue-tongue lizard is big.", "Bajabaja yalbay.",
        "bajabaja yalbay | blue-tongue.lizard big", "r147_state_bluetongue_lizard_big", ["bajabaja", "yalbay"], "Bajabaja blue-tongue lizard animal sense only; no story-site row."),
    row(8, "The pig is in the scrub.", "Bikibiki madja-nga.",
        "bikibiki madja-nga | pig scrub-LOC", "r147_location_pig_scrub", ["bikibiki", "madja"], "Bikibiki bare target with support locative madja-nga."),
    row(9, "The wallaby is on the open ground.", "Kadar ngalkal-ba.",
        "kadar ngalkal-ba | wallaby open.ground-LOC", "r147_location_wallaby_open", ["kadar", "ngalkal"], "Kadar bare target with support locative ngalkal-ba."),
    row(10, "The grey kangaroo is on the open ground.", "Julmbanu ngalkal-ba.",
        "julmbanu ngalkal-ba | grey.kangaroo open.ground-LOC", "r147_location_grey_kangaroo_open", ["julmbanu", "ngalkal"], "Julmbanu bare target with support locative ngalkal-ba."),
    row(11, "The dog is at the camp.", "Kaya bayan-ba.",
        "kaya bayan-ba | dog camp-LOC", "r147_location_dog_camp", ["kaya", "bayan"], "Kaya dog with support locative bayan-ba camp/house LOC."),
    row(12, "The black scrub goanna is in the scrub.", "Walkarr madja-nga.",
        "walkarr madja-nga | black.scrub.goanna scrub-LOC", "r147_location_goanna_scrub", ["walkarr", "madja"], "Walkarr bare target with support locative madja-nga."),
    row(13, "The snake is in the scrub.", "Jarba madja-nga.",
        "jarba madja-nga | snake scrub-LOC", "r147_location_snake_scrub", ["jarba", "madja"], "Jarba generic snake with support locative; no bite/fear row."),
    row(14, "The blue-tongue lizard is on the ground.", "Bajabaja bubu-ngu.",
        "bajabaja bubu-ngu | blue-tongue.lizard ground-LOC", "r147_location_bluetongue_ground", ["bajabaja", "bubu"], "Bajabaja animal sense with support locative bubu-ngu."),
    row(15, "The pig is at the camp.", "Bikibiki bayan-ba.",
        "bikibiki bayan-ba | pig camp-LOC", "r147_location_pig_camp", ["bikibiki", "bayan"], "Bikibiki bare target with support locative bayan-ba."),
    row(16, "The wallaby is in the scrub.", "Kadar madja-nga.",
        "kadar madja-nga | wallaby scrub-LOC", "r147_location_wallaby_scrub", ["kadar", "madja"], "Kadar bare target with support locative madja-nga."),
    row(17, "The grey kangaroo is in the scrub.", "Julmbanu madja-nga.",
        "julmbanu madja-nga | grey.kangaroo scrub-LOC", "r147_location_grey_kangaroo_scrub", ["julmbanu", "madja"], "Julmbanu bare target with support locative madja-nga."),
    row(18, "The dog is outside.", "Kaya ngalkal-ba.",
        "kaya ngalkal-ba | dog outside-LOC", "r147_location_dog_outside", ["kaya", "ngalkal"], "Kaya dog with support locative ngalkal-ba outside/open ground."),
    row(19, "The black scrub goanna is on the ground.", "Walkarr bubu-ngu.",
        "walkarr bubu-ngu | black.scrub.goanna ground-LOC", "r147_location_goanna_ground", ["walkarr", "bubu"], "Walkarr bare target with support locative bubu-ngu."),
    row(20, "The snake is on the open ground.", "Jarba ngalkal-ba.",
        "jarba ngalkal-ba | snake open.ground-LOC", "r147_location_snake_open", ["jarba", "ngalkal"], "Jarba generic snake with support locative ngalkal-ba."),
    row(21, "The blue-tongue lizard is in the scrub.", "Bajabaja madja-nga.",
        "bajabaja madja-nga | blue-tongue.lizard scrub-LOC", "r147_location_bluetongue_scrub", ["bajabaja", "madja"], "Bajabaja animal sense with support locative madja-nga."),
    row(22, "Mother saw the pig.", "Ngamu-ngku bikibiki nyajin.",
        "ngamu-ngku bikibiki nyaji-ny | mother-ERG pig see-PAST", "r147_perception_mother_pig", ["ngamu", "bikibiki", "nyaji-l"], "Common-noun A ERG; bikibiki bare object."),
    row(23, "Father saw the wallaby.", "Nganjan-angka kadar nyajin.",
        "nganjan-angka kadar nyaji-ny | father-ERG wallaby see-PAST", "r147_perception_father_wallaby", ["nganjan", "kadar", "nyaji-l"], "Common-noun A ERG; kadar bare object."),
    row(24, "Grandmother saw the grey kangaroo.", "Babi-ngka julmbanu nyajin.",
        "babi-ngka julmbanu nyaji-ny | grandmother-ERG grey.kangaroo see-PAST", "r147_perception_grandmother_grey_kangaroo", ["babi", "julmbanu", "nyaji-l"], "Common-noun A ERG; julmbanu bare object."),
    row(25, "The child saw the dog.", "Karrkay-ngku kaya nyajin.",
        "karrkay-ngku kaya nyaji-ny | child-ERG dog see-PAST", "r147_perception_child_dog", ["karrkay", "kaya", "nyaji-l"], "Common-noun A ERG; kaya bare object."),
    row(26, "Grandfather saw the black scrub goanna.", "Kami-ngka walkarr nyajin.",
        "kami-ngka walkarr nyaji-ny | grandfather-ERG black.scrub.goanna see-PAST", "r147_perception_grandfather_goanna", ["kami", "walkarr", "nyaji-l"], "Common-noun A ERG; walkarr bare object."),
    row(27, "The woman saw the snake.", "Jalbu-ngku jarba nyajin.",
        "jalbu-ngku jarba nyaji-ny | woman-ERG snake see-PAST", "r147_perception_woman_snake", ["jalbu", "jarba", "nyaji-l"], "Common-noun A ERG; jarba bare object."),
    row(28, "The man saw the blue-tongue lizard.", "Dingkar-angka bajabaja nyajin.",
        "dingkar-angka bajabaja nyaji-ny | man-ERG blue-tongue.lizard see-PAST", "r147_perception_man_bluetongue", ["dingkar", "bajabaja", "nyaji-l"], "Common-noun A ERG; bajabaja animal object."),
    row(29, "I saw the pig in the scrub.", "Ngayu bikibiki madja-nga nyajin.",
        "ngayu bikibiki madja-nga nyaji-ny | I pig scrub-LOC see-PAST", "r147_perception_i_pig_scrub", ["ngayu", "bikibiki", "madja", "nyaji-l"], "Pronoun A bare; support locative madja-nga."),
    row(30, "We saw the wallaby on the open ground.", "Ngana kadar ngalkal-ba nyajin.",
        "ngana kadar ngalkal-ba nyaji-ny | we wallaby open.ground-LOC see-PAST", "r147_perception_we_wallaby_open", ["ngana", "kadar", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(31, "They saw the grey kangaroo on the open ground.", "Jana julmbanu ngalkal-ba nyajin.",
        "jana julmbanu ngalkal-ba nyaji-ny | they grey.kangaroo open.ground-LOC see-PAST", "r147_perception_they_grey_kangaroo_open", ["jana", "julmbanu", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(32, "Mother saw the dog at the camp.", "Ngamu-ngku kaya bayan-ba nyajin.",
        "ngamu-ngku kaya bayan-ba nyaji-ny | mother-ERG dog camp-LOC see-PAST", "r147_perception_mother_dog_camp", ["ngamu", "kaya", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(33, "Father saw the black scrub goanna in the scrub.", "Nganjan-angka walkarr madja-nga nyajin.",
        "nganjan-angka walkarr madja-nga nyaji-ny | father-ERG black.scrub.goanna scrub-LOC see-PAST", "r147_perception_father_goanna_scrub", ["nganjan", "walkarr", "madja", "nyaji-l"], "Common-noun A ERG; walkarr animal sense only."),
    row(34, "Grandmother saw the snake in the scrub.", "Babi-ngka jarba madja-nga nyajin.",
        "babi-ngka jarba madja-nga nyaji-ny | grandmother-ERG snake scrub-LOC see-PAST", "r147_perception_grandmother_snake_scrub", ["babi", "jarba", "madja", "nyaji-l"], "Common-noun A ERG; no bite/fear row."),
    row(35, "The child saw the blue-tongue lizard on the ground.", "Karrkay-ngku bajabaja bubu-ngu nyajin.",
        "karrkay-ngku bajabaja bubu-ngu nyaji-ny | child-ERG blue-tongue.lizard ground-LOC see-PAST", "r147_perception_child_bluetongue_ground", ["karrkay", "bajabaja", "bubu", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(36, "Grandfather saw the pig at the camp.", "Kami-ngka bikibiki bayan-ba nyajin.",
        "kami-ngka bikibiki bayan-ba nyaji-ny | grandfather-ERG pig camp-LOC see-PAST", "r147_perception_grandfather_pig_camp", ["kami", "bikibiki", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(37, "The woman saw the wallaby in the scrub.", "Jalbu-ngku kadar madja-nga nyajin.",
        "jalbu-ngku kadar madja-nga nyaji-ny | woman-ERG wallaby scrub-LOC see-PAST", "r147_perception_woman_wallaby_scrub", ["jalbu", "kadar", "madja", "nyaji-l"], "Common-noun A ERG; support locative madja-nga."),
    row(38, "The man saw the grey kangaroo in the scrub.", "Dingkar-angka julmbanu madja-nga nyajin.",
        "dingkar-angka julmbanu madja-nga nyaji-ny | man-ERG grey.kangaroo scrub-LOC see-PAST", "r147_perception_man_grey_kangaroo_scrub", ["dingkar", "julmbanu", "madja", "nyaji-l"], "Common-noun A ERG; julmbanu object."),
    row(39, "I saw the dog outside.", "Ngayu kaya ngalkal-ba nyajin.",
        "ngayu kaya ngalkal-ba nyaji-ny | I dog outside-LOC see-PAST", "r147_perception_i_dog_outside", ["ngayu", "kaya", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(40, "We saw the black scrub goanna on the ground.", "Ngana walkarr bubu-ngu nyajin.",
        "ngana walkarr bubu-ngu nyaji-ny | we black.scrub.goanna ground-LOC see-PAST", "r147_perception_we_goanna_ground", ["ngana", "walkarr", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(41, "They saw the snake on the open ground.", "Jana jarba ngalkal-ba nyajin.",
        "jana jarba ngalkal-ba nyaji-ny | they snake open.ground-LOC see-PAST", "r147_perception_they_snake_open", ["jana", "jarba", "ngalkal", "nyaji-l"], "Pronoun A bare; no bite/fear/poison row."),
    row(42, "Mother saw the blue-tongue lizard in the scrub.", "Ngamu-ngku bajabaja madja-nga nyajin.",
        "ngamu-ngku bajabaja madja-nga nyaji-ny | mother-ERG blue-tongue.lizard scrub-LOC see-PAST", "r147_perception_mother_bluetongue_scrub", ["ngamu", "bajabaja", "madja", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(43, "I see the dog at the camp.", "Ngayu kaya bayan-ba nyajil.",
        "ngayu kaya bayan-ba nyaji-l | I dog camp-LOC see-NONPAST", "r147_present_i_dog_camp", ["ngayu", "kaya", "bayan", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(44, "We see the black scrub goanna in the scrub.", "Ngana walkarr madja-nga nyajil.",
        "ngana walkarr madja-nga nyaji-l | we black.scrub.goanna scrub-LOC see-NONPAST", "r147_present_we_goanna_scrub", ["ngana", "walkarr", "madja", "nyaji-l"], "Pronoun A bare; support locative madja-nga."),
    row(45, "They see the snake on the open ground.", "Jana jarba ngalkal-ba nyajil.",
        "jana jarba ngalkal-ba nyaji-l | they snake open.ground-LOC see-NONPAST", "r147_present_they_snake_open", ["jana", "jarba", "ngalkal", "nyaji-l"], "Pronoun A bare; no bite/fear row."),
    row(46, "Mother sees the pig at the camp.", "Ngamu-ngku bikibiki bayan-ba nyajil.",
        "ngamu-ngku bikibiki bayan-ba nyaji-l | mother-ERG pig camp-LOC see-NONPAST", "r147_present_mother_pig_camp", ["ngamu", "bikibiki", "bayan", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(47, "Father sees the wallaby in the scrub.", "Nganjan-angka kadar madja-nga nyajil.",
        "nganjan-angka kadar madja-nga nyaji-l | father-ERG wallaby scrub-LOC see-NONPAST", "r147_present_father_wallaby_scrub", ["nganjan", "kadar", "madja", "nyaji-l"], "Common-noun A ERG; support locative madja-nga."),
    row(48, "Grandmother sees the grey kangaroo on the open ground.", "Babi-ngka julmbanu ngalkal-ba nyajil.",
        "babi-ngka julmbanu ngalkal-ba nyaji-l | grandmother-ERG grey.kangaroo open.ground-LOC see-NONPAST", "r147_present_grandmother_grey_kangaroo_open", ["babi", "julmbanu", "ngalkal", "nyaji-l"], "Common-noun A ERG; support locative ngalkal-ba."),
    row(49, "The woman sees the blue-tongue lizard on the ground.", "Jalbu-ngku bajabaja bubu-ngu nyajil.",
        "jalbu-ngku bajabaja bubu-ngu nyaji-l | woman-ERG blue-tongue.lizard ground-LOC see-NONPAST", "r147_present_woman_bluetongue_ground", ["jalbu", "bajabaja", "bubu", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(50, "The man sees the black scrub goanna on the ground.", "Dingkar-angka walkarr bubu-ngu nyajil.",
        "dingkar-angka walkarr bubu-ngu nyaji-l | man-ERG black.scrub.goanna ground-LOC see-NONPAST", "r147_present_man_goanna_ground", ["dingkar", "walkarr", "bubu", "nyaji-l"], "Common-noun A ERG; walkarr animal sense only."),
]


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|muny|bu|ji|jirr|ku|mundu|amu|mu)\b", 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)
        loans = json.loads(loans_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("r147_"):
            issues.append(f"{label}: Rule 147 frame must start with r147_")
        if low in seen_ku:
            issues.append(f"{label}: duplicate Kuku surface within batch")
        seen_ku.add(low)
        if loans and loans != ["bikibiki"]:
            issues.append(f"{label}: only the source-backed bikibiki loan is allowed")
        if has_token(low, "bikibiki") and loans != ["bikibiki"]:
            issues.append(f"{label}: bikibiki loan must be recorded in loans_used")
        for denied in DENY:
            if has_token(low, denied):
                issues.append(f"{label}: denied or out-of-scope 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 147 target head, found {targets}")
        for head in targets:
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if TARGET_HEADS[head] not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {TARGET_HEADS[head]}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        for form in re.findall(r"\b[a-z]+-(?:nga|ba|muny|ngu)\b", low):
            if form not in SUPPORT_FORMS:
                issues.append(f"{label}: unapproved support local form {form}")
        for support, head in {"madja-nga": "madja", "ngalkal-ba": "ngalkal", "bayan-ba": "bayan", "bubu-ngu": "bubu"}.items():
            if has_token(low, support) and head not in words:
                issues.append(f"{label}: support head {head} missing from words_used")
        if has_token(low, "bikibiki") and "pig" not in english_low:
            issues.append(f"{label}: bikibiki must be pig")
        if has_token(low, "kadar") and "wallaby" not in english_low:
            issues.append(f"{label}: kadar must be wallaby")
        if has_token(low, "julmbanu") and "grey kangaroo" not in english_low:
            issues.append(f"{label}: julmbanu must be grey kangaroo")
        if has_token(low, "kaya") and "dog" not in english_low:
            issues.append(f"{label}: kaya must be dog")
        if has_token(low, "walkarr") and "black scrub goanna" not in english_low:
            issues.append(f"{label}: walkarr must be black scrub goanna")
        if has_token(low, "jarba") and "snake" not in english_low:
            issues.append(f"{label}: jarba must be snake")
        if has_token(low, "bajabaja") and "blue-tongue lizard" not in english_low:
            issues.append(f"{label}: bajabaja must be blue-tongue lizard")
        if "-bu" in low or "INST" in analysis:
            issues.append(f"{label}: no instrument morphology in Rule 147")
        if any(bad in english_low for bad in DENIED_ENGLISH):
            issues.append(f"{label}: denied animal-use/danger/story field in English")
        if "nyajin" in low or "nyajil" in low:
            first = first_word(low)
            if first not in PRONOUN_A and first not in COMMON_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun or ERG-marked common noun")
        if "nyajil" in low and "see-NONPAST" not in analysis:
            issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        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 147 draft: land-animal lexical expansion after Rule 146", "operator-guide-2026-07-07", "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 147 source pass selected seven land-animal target heads after dictionary, Patz grammar, lexeme-table, "
            "and corpus-surface readback: bikibiki pig, kadar wallaby, julmbanu grey kangaroo, kaya dog, walkarr black "
            "scrub goanna, jarba generic snake, and bajabaja blue-tongue lizard. Bulki was excluded because no exact "
            "dictionary entry exists in the parsed dictionary file."
        ),
        command="dictionary.yaml structured readback; grammar.md exact occurrence readback; sqlite lexeme and duplicate 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 147 admits land-animal name rows only: size-state, support-only locative nominal clauses, past "
            "perception, and present perception. It excludes hunting, killing, spearing, shooting, chasing, catching, "
            "cutting, biting, licking, eating, meat, food, poison, sickness, fear, taboo, storm, story, myth, totem, "
            "track, egg, tail, teeth, dog possession, and animal-behaviour ecology."
        ),
        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 cross-corpus duplicates.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_189.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guards passed: one land-animal target per row, bikibiki loan recorded, no target case forms, no instruments, approved support locatives only, no animal-use/danger/story field, common-noun A ERG, and pronoun A bare.",
        command="python3 batch_scripts/bank_189.py static scan",
        artifact_path="batch_scripts/bank_189.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (batch_id, seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence,
             "under_review", confidence, "claude-main", NOW, NOW)
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="bank",
        event_type="bank-success",
        actor="claude-main",
        detail="Banked 50 under_review Rule 147 land-animal lexical-expansion rows.",
        command="python3 batch_scripts/bank_189.py",
        artifact_path="batch_scripts/bank_189.py",
        created_at=NOW,
    )
    db.commit()

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


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