#!/usr/bin/env python3
"""Bank batch-190: Rule 148 construction consolidation after Rule 147."""

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-190"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-190-construction-consolidation-after-rule147-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 on the open ground.", "Bikibiki ngalkal-ba.",
        "bikibiki ngalkal-ba | pig open.ground-LOC", "r148_location_pig_open", ["bikibiki", "ngalkal"], "Rule 148 retained target with support locative ngalkal-ba."),
    row(2, "The pig is on the ground.", "Bikibiki bubu-ngu.",
        "bikibiki bubu-ngu | pig ground-LOC", "r148_location_pig_ground", ["bikibiki", "bubu"], "Rule 148 retained target with support locative bubu-ngu."),
    row(3, "The wallaby is at the camp.", "Kadar bayan-ba.",
        "kadar bayan-ba | wallaby camp-LOC", "r148_location_wallaby_camp", ["kadar", "bayan"], "Rule 148 retained target with support locative bayan-ba."),
    row(4, "The wallaby is on the ground.", "Kadar bubu-ngu.",
        "kadar bubu-ngu | wallaby ground-LOC", "r148_location_wallaby_ground", ["kadar", "bubu"], "Rule 148 retained target with support locative bubu-ngu."),
    row(5, "The grey kangaroo is at the camp.", "Julmbanu bayan-ba.",
        "julmbanu bayan-ba | grey.kangaroo camp-LOC", "r148_location_grey_kangaroo_camp", ["julmbanu", "bayan"], "Rule 148 retained target with support locative bayan-ba."),
    row(6, "The grey kangaroo is on the ground.", "Julmbanu bubu-ngu.",
        "julmbanu bubu-ngu | grey.kangaroo ground-LOC", "r148_location_grey_kangaroo_ground", ["julmbanu", "bubu"], "Rule 148 retained target with support locative bubu-ngu."),
    row(7, "The dog is in the scrub.", "Kaya madja-nga.",
        "kaya madja-nga | dog scrub-LOC", "r148_location_dog_scrub", ["kaya", "madja"], "Rule 148 retained dog target with support locative madja-nga."),
    row(8, "The dog is on the ground.", "Kaya bubu-ngu.",
        "kaya bubu-ngu | dog ground-LOC", "r148_location_dog_ground", ["kaya", "bubu"], "Rule 148 retained dog target with support locative bubu-ngu."),
    row(9, "The black scrub goanna is on the open ground.", "Walkarr ngalkal-ba.",
        "walkarr ngalkal-ba | black.scrub.goanna open.ground-LOC", "r148_location_goanna_open", ["walkarr", "ngalkal"], "Rule 148 retained walkarr target with support locative ngalkal-ba."),
    row(10, "The black scrub goanna is at the camp.", "Walkarr bayan-ba.",
        "walkarr bayan-ba | black.scrub.goanna camp-LOC", "r148_location_goanna_camp", ["walkarr", "bayan"], "Rule 148 retained walkarr target with support locative bayan-ba."),
    row(11, "The snake is at the camp.", "Jarba bayan-ba.",
        "jarba bayan-ba | snake camp-LOC", "r148_location_snake_camp", ["jarba", "bayan"], "Rule 148 retained jarba target; no bite/fear row."),
    row(12, "The snake is on the ground.", "Jarba bubu-ngu.",
        "jarba bubu-ngu | snake ground-LOC", "r148_location_snake_ground", ["jarba", "bubu"], "Rule 148 retained jarba target with support locative bubu-ngu."),
    row(13, "The blue-tongue lizard is on the open ground.", "Bajabaja ngalkal-ba.",
        "bajabaja ngalkal-ba | blue-tongue.lizard open.ground-LOC", "r148_location_bluetongue_open", ["bajabaja", "ngalkal"], "Rule 148 retained bajabaja animal sense with support locative ngalkal-ba."),
    row(14, "The blue-tongue lizard is at the camp.", "Bajabaja bayan-ba.",
        "bajabaja bayan-ba | blue-tongue.lizard camp-LOC", "r148_location_bluetongue_camp", ["bajabaja", "bayan"], "Rule 148 retained bajabaja animal sense with support locative bayan-ba."),
    row(15, "The child saw the pig.", "Karrkay-ngku bikibiki nyajin.",
        "karrkay-ngku bikibiki nyaji-ny | child-ERG pig see-PAST", "r148_perception_child_pig", ["karrkay", "bikibiki", "nyaji-l"], "Common-noun A ERG; retained pig object."),
    row(16, "Grandfather saw the wallaby.", "Kami-ngka kadar nyajin.",
        "kami-ngka kadar nyaji-ny | grandfather-ERG wallaby see-PAST", "r148_perception_grandfather_wallaby", ["kami", "kadar", "nyaji-l"], "Common-noun A ERG; retained wallaby object."),
    row(17, "The woman saw the grey kangaroo.", "Jalbu-ngku julmbanu nyajin.",
        "jalbu-ngku julmbanu nyaji-ny | woman-ERG grey.kangaroo see-PAST", "r148_perception_woman_grey_kangaroo", ["jalbu", "julmbanu", "nyaji-l"], "Common-noun A ERG; retained grey kangaroo object."),
    row(18, "The man saw the dog.", "Dingkar-angka kaya nyajin.",
        "dingkar-angka kaya nyaji-ny | man-ERG dog see-PAST", "r148_perception_man_dog", ["dingkar", "kaya", "nyaji-l"], "Common-noun A ERG; retained dog object."),
    row(19, "Mother saw the black scrub goanna.", "Ngamu-ngku walkarr nyajin.",
        "ngamu-ngku walkarr nyaji-ny | mother-ERG black.scrub.goanna see-PAST", "r148_perception_mother_goanna", ["ngamu", "walkarr", "nyaji-l"], "Common-noun A ERG; retained goanna object."),
    row(20, "Father saw the snake.", "Nganjan-angka jarba nyajin.",
        "nganjan-angka jarba nyaji-ny | father-ERG snake see-PAST", "r148_perception_father_snake", ["nganjan", "jarba", "nyaji-l"], "Common-noun A ERG; generic snake only."),
    row(21, "Grandmother saw the blue-tongue lizard.", "Babi-ngka bajabaja nyajin.",
        "babi-ngka bajabaja nyaji-ny | grandmother-ERG blue-tongue.lizard see-PAST", "r148_perception_grandmother_bluetongue", ["babi", "bajabaja", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(22, "I saw the wallaby.", "Ngayu kadar nyajin.",
        "ngayu kadar nyaji-ny | I wallaby see-PAST", "r148_perception_i_wallaby", ["ngayu", "kadar", "nyaji-l"], "Pronoun A bare; retained wallaby object."),
    row(23, "We saw the dog.", "Ngana kaya nyajin.",
        "ngana kaya nyaji-ny | we dog see-PAST", "r148_perception_we_dog", ["ngana", "kaya", "nyaji-l"], "Pronoun A bare; retained dog object."),
    row(24, "They saw the black scrub goanna.", "Jana walkarr nyajin.",
        "jana walkarr nyaji-ny | they black.scrub.goanna see-PAST", "r148_perception_they_goanna", ["jana", "walkarr", "nyaji-l"], "Pronoun A bare; retained goanna object."),
    row(25, "I saw the snake.", "Ngayu jarba nyajin.",
        "ngayu jarba nyaji-ny | I snake see-PAST", "r148_perception_i_snake", ["ngayu", "jarba", "nyaji-l"], "Pronoun A bare; no bite/fear row."),
    row(26, "We saw the blue-tongue lizard.", "Ngana bajabaja nyajin.",
        "ngana bajabaja nyaji-ny | we blue-tongue.lizard see-PAST", "r148_perception_we_bluetongue", ["ngana", "bajabaja", "nyaji-l"], "Pronoun A bare; bajabaja animal sense only."),
    row(27, "They saw the pig.", "Jana bikibiki nyajin.",
        "jana bikibiki nyaji-ny | they pig see-PAST", "r148_perception_they_pig", ["jana", "bikibiki", "nyaji-l"], "Pronoun A bare; retained pig object."),
    row(28, "I saw the grey kangaroo.", "Ngayu julmbanu nyajin.",
        "ngayu julmbanu nyaji-ny | I grey.kangaroo see-PAST", "r148_perception_i_grey_kangaroo", ["ngayu", "julmbanu", "nyaji-l"], "Pronoun A bare; retained grey kangaroo object."),
    row(29, "I saw the pig on the open ground.", "Ngayu bikibiki ngalkal-ba nyajin.",
        "ngayu bikibiki ngalkal-ba nyaji-ny | I pig open.ground-LOC see-PAST", "r148_perception_i_pig_open", ["ngayu", "bikibiki", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(30, "We saw the wallaby at the camp.", "Ngana kadar bayan-ba nyajin.",
        "ngana kadar bayan-ba nyaji-ny | we wallaby camp-LOC see-PAST", "r148_perception_we_wallaby_camp", ["ngana", "kadar", "bayan", "nyaji-l"], "Pronoun A bare; support locative bayan-ba."),
    row(31, "They saw the grey kangaroo on the ground.", "Jana julmbanu bubu-ngu nyajin.",
        "jana julmbanu bubu-ngu nyaji-ny | they grey.kangaroo ground-LOC see-PAST", "r148_perception_they_grey_kangaroo_ground", ["jana", "julmbanu", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(32, "Mother saw the dog in the scrub.", "Ngamu-ngku kaya madja-nga nyajin.",
        "ngamu-ngku kaya madja-nga nyaji-ny | mother-ERG dog scrub-LOC see-PAST", "r148_perception_mother_dog_scrub", ["ngamu", "kaya", "madja", "nyaji-l"], "Common-noun A ERG; support locative madja-nga."),
    row(33, "Father saw the black scrub goanna at the camp.", "Nganjan-angka walkarr bayan-ba nyajin.",
        "nganjan-angka walkarr bayan-ba nyaji-ny | father-ERG black.scrub.goanna camp-LOC see-PAST", "r148_perception_father_goanna_camp", ["nganjan", "walkarr", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(34, "Grandmother saw the snake on the ground.", "Babi-ngka jarba bubu-ngu nyajin.",
        "babi-ngka jarba bubu-ngu nyaji-ny | grandmother-ERG snake ground-LOC see-PAST", "r148_perception_grandmother_snake_ground", ["babi", "jarba", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(35, "The child saw the blue-tongue lizard on the open ground.", "Karrkay-ngku bajabaja ngalkal-ba nyajin.",
        "karrkay-ngku bajabaja ngalkal-ba nyaji-ny | child-ERG blue-tongue.lizard open.ground-LOC see-PAST", "r148_perception_child_bluetongue_open", ["karrkay", "bajabaja", "ngalkal", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(36, "Grandfather saw the pig on the ground.", "Kami-ngka bikibiki bubu-ngu nyajin.",
        "kami-ngka bikibiki bubu-ngu nyaji-ny | grandfather-ERG pig ground-LOC see-PAST", "r148_perception_grandfather_pig_ground", ["kami", "bikibiki", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(37, "The woman saw the wallaby on the ground.", "Jalbu-ngku kadar bubu-ngu nyajin.",
        "jalbu-ngku kadar bubu-ngu nyaji-ny | woman-ERG wallaby ground-LOC see-PAST", "r148_perception_woman_wallaby_ground", ["jalbu", "kadar", "bubu", "nyaji-l"], "Common-noun A ERG; support locative bubu-ngu."),
    row(38, "The man saw the grey kangaroo at the camp.", "Dingkar-angka julmbanu bayan-ba nyajin.",
        "dingkar-angka julmbanu bayan-ba nyaji-ny | man-ERG grey.kangaroo camp-LOC see-PAST", "r148_perception_man_grey_kangaroo_camp", ["dingkar", "julmbanu", "bayan", "nyaji-l"], "Common-noun A ERG; support locative bayan-ba."),
    row(39, "I saw the dog on the ground.", "Ngayu kaya bubu-ngu nyajin.",
        "ngayu kaya bubu-ngu nyaji-ny | I dog ground-LOC see-PAST", "r148_perception_i_dog_ground", ["ngayu", "kaya", "bubu", "nyaji-l"], "Pronoun A bare; support locative bubu-ngu."),
    row(40, "We saw the black scrub goanna on the open ground.", "Ngana walkarr ngalkal-ba nyajin.",
        "ngana walkarr ngalkal-ba nyaji-ny | we black.scrub.goanna open.ground-LOC see-PAST", "r148_perception_we_goanna_open", ["ngana", "walkarr", "ngalkal", "nyaji-l"], "Pronoun A bare; support locative ngalkal-ba."),
    row(41, "They saw the snake at the camp.", "Jana jarba bayan-ba nyajin.",
        "jana jarba bayan-ba nyaji-ny | they snake camp-LOC see-PAST", "r148_perception_they_snake_camp", ["jana", "jarba", "bayan", "nyaji-l"], "Pronoun A bare; no bite/fear row."),
    row(42, "Mother saw the blue-tongue lizard at the camp.", "Ngamu-ngku bajabaja bayan-ba nyajin.",
        "ngamu-ngku bajabaja bayan-ba nyaji-ny | mother-ERG blue-tongue.lizard camp-LOC see-PAST", "r148_perception_mother_bluetongue_camp", ["ngamu", "bajabaja", "bayan", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(43, "I see the pig.", "Ngayu bikibiki nyajil.",
        "ngayu bikibiki nyaji-l | I pig see-NONPAST", "r148_present_i_pig", ["ngayu", "bikibiki", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(44, "We see the wallaby.", "Ngana kadar nyajil.",
        "ngana kadar nyaji-l | we wallaby see-NONPAST", "r148_present_we_wallaby", ["ngana", "kadar", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(45, "They see the grey kangaroo.", "Jana julmbanu nyajil.",
        "jana julmbanu nyaji-l | they grey.kangaroo see-NONPAST", "r148_present_they_grey_kangaroo", ["jana", "julmbanu", "nyaji-l"], "Pronoun A bare; nyaji-l nonpast."),
    row(46, "Mother sees the dog.", "Ngamu-ngku kaya nyajil.",
        "ngamu-ngku kaya nyaji-l | mother-ERG dog see-NONPAST", "r148_present_mother_dog", ["ngamu", "kaya", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(47, "Father sees the black scrub goanna.", "Nganjan-angka walkarr nyajil.",
        "nganjan-angka walkarr nyaji-l | father-ERG black.scrub.goanna see-NONPAST", "r148_present_father_goanna", ["nganjan", "walkarr", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
    row(48, "Grandmother sees the snake.", "Babi-ngka jarba nyajil.",
        "babi-ngka jarba nyaji-l | grandmother-ERG snake see-NONPAST", "r148_present_grandmother_snake", ["babi", "jarba", "nyaji-l"], "Common-noun A ERG; no bite/fear row."),
    row(49, "The child sees the blue-tongue lizard.", "Karrkay-ngku bajabaja nyajil.",
        "karrkay-ngku bajabaja nyaji-l | child-ERG blue-tongue.lizard see-NONPAST", "r148_present_child_bluetongue", ["karrkay", "bajabaja", "nyaji-l"], "Common-noun A ERG; bajabaja animal sense only."),
    row(50, "The man sees the pig.", "Dingkar-angka bikibiki nyajil.",
        "dingkar-angka bikibiki nyaji-l | man-ERG pig see-NONPAST", "r148_present_man_pig", ["dingkar", "bikibiki", "nyaji-l"], "Common-noun A ERG; nyaji-l nonpast."),
]


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("r148_"):
            issues.append(f"{label}: Rule 148 frame must start with r148_")
        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 148 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 148")
        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 148 draft: construction consolidation after Rule 147", "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 148 source pass admitted no new target heads. It retained Rule 147 land-animal names and "
            "source-checked support/perception forms: madja-nga, ngalkal-ba, bayan-ba, bubu-ngu, nyaji-ny past, and "
            "nyaji-l nonpast. Dictionary, grammar, lexeme-table, and corpus-surface readback completed."
        ),
        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="construction-scope",
        actor="claude-main",
        detail=(
            "Rule 148 consolidates land-animal heads in support-location and perception frames only. It excludes "
            "hunting, killing, spearing, shooting, chasing, catching, cutting, biting, licking, barking, eating, meat, "
            "food, poison, sickness, fear, taboo, storm, story, myth, totem, track, egg, tail, teeth, biki, bulki, "
            "target case forms, instruments, 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_190.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 retained 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_190.py static scan",
        artifact_path="batch_scripts/bank_190.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 148 land-animal construction-consolidation rows.",
        command="python3 batch_scripts/bank_190.py",
        artifact_path="batch_scripts/bank_190.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())
