#!/usr/bin/env python3
"""Bank batch-217: Rule 175 reptile reference lexical expansion after Rule 174."""

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

TARGET_HEADS = {
    "banamu": "fresh water snake",
    "binju": "light bellied black snake",
    "dukul-mukul": "dukul-mukul lizard",
    "jirabay": "ground lizard",
    "junbirr": "small lizard",
    "kabuljaka": "striped water snake",
    "kulmba-kulmba": "gecko",
    "kurriyala": "carpet snake",
    "ngawurr-ngawun": "freshwater crocodile",
    "ngumbul": "sea snake",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "jarba", "wali-yindu-wali-yindu", "jalbil", "kalkarrumbarr", "kurmba-kurmba", "jimalili",
    "yuday", "barka", "bajabaja", "jadi", "jinkalmu", "bajalji", "kalajarr", "bilngkumu",
    "ngawiya", "walkarr", "bakay", "bubal", "jabil", "kungkun", "kundurr", "bindimu",
    "kalkamuku", "yirku-yirku",
}
DENY_ENGLISH = (
    "wrong marriage", "marriage", "cooking", "cooked", "cook", "poison", "poisonous", "fish", "grunter",
    "belt", "run", "runs", "running", "story", "story-site", "legend", "myth", "mythological", "food",
    "edible", "eat", "eats", "ate", "eaten", "hunt", "hunting", "catch", "catches", "caught", "chase",
    "chases", "chased", "firestick", "eye", "eyes", "fighter", "fierce", "place", "place-name", "river",
    "egg", "eggs", "body-part", "head", "belly", "marking", "markings", "use", "uses", "made",
)


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


ROWS = [
    row(1, "The fresh water snake is here.", "Banamu yaluy.", "banamu yaluy | fresh.water.snake here", "r175_deictic_banamu_here", ["banamu", "yaluy"], "Rule 175 admits banamu as fresh water snake; reference only."),
    row(2, "The light bellied black snake is here.", "Binju yaluy.", "binju yaluy | light.bellied.black.snake here", "r175_deictic_binju_here", ["binju", "yaluy"], "Rule 175 admits binju as light bellied black snake; wrong-marriage/cooking/poison senses remain closed."),
    row(3, "The dukul-mukul lizard is here.", "Dukul-mukul yaluy.", "dukul-mukul yaluy | dukul-mukul.lizard here", "r175_deictic_dukulmukul_here", ["dukul-mukul", "yaluy"], "Rule 175 admits dukul-mukul as a lizard head; big-head prose not imported."),
    row(4, "The ground lizard is here.", "Jirabay yaluy.", "jirabay yaluy | ground.lizard here", "r175_deictic_jirabay_here", ["jirabay", "yaluy"], "Rule 175 admits jirabay as ground lizard; comparison prose not imported."),
    row(5, "The small lizard is here.", "Junbirr yaluy.", "junbirr yaluy | small.lizard here", "r175_deictic_junbirr_here", ["junbirr", "yaluy"], "Rule 175 admits junbirr as small lizard; seasonal/marking prose not imported."),
    row(6, "The striped water snake is here.", "Kabuljaka yaluy.", "kabuljaka yaluy | striped.water.snake here", "r175_deictic_kabuljaka_here", ["kabuljaka", "yaluy"], "Rule 175 admits kabuljaka as striped water snake; reference only."),
    row(7, "The gecko is here.", "Kulmba-kulmba yaluy.", "kulmba-kulmba yaluy | gecko here", "r175_deictic_kulmbakulmba_here", ["kulmba-kulmba", "yaluy"], "Rule 175 admits kulmba-kulmba as gecko; whole lexical head."),
    row(8, "The carpet snake is here.", "Kurriyala yaluy.", "kurriyala yaluy | carpet.snake here", "r175_deictic_kurriyala_here", ["kurriyala", "yaluy"], "Rule 175 admits kurriyala as carpet snake; fish, story, belt-source, and run-away prose remain closed."),
    row(9, "The freshwater crocodile is here.", "Ngawurr-ngawun yaluy.", "ngawurr-ngawun yaluy | freshwater.crocodile here", "r175_deictic_ngawurrngawun_here", ["ngawurr-ngawun", "yaluy"], "Rule 175 admits ngawurr-ngawun as freshwater crocodile; reference only."),
    row(10, "The sea snake is here.", "Ngumbul yaluy.", "ngumbul yaluy | sea.snake here", "r175_deictic_ngumbul_here", ["ngumbul", "yaluy"], "Rule 175 admits ngumbul as sea snake; reference only."),
    row(11, "I see the fresh water snake.", "Ngayu banamu nyajil.", "ngayu banamu nyaji-l | I fresh.water.snake see-NONPAST", "r175_present_i_banamu", ["ngayu", "banamu", "nyaji-l"], "Pronoun A bare; banamu object bare."),
    row(12, "I see the light bellied black snake.", "Ngayu binju nyajil.", "ngayu binju nyaji-l | I light.bellied.black.snake see-NONPAST", "r175_present_i_binju", ["ngayu", "binju", "nyaji-l"], "Pronoun A bare; selected reptile sense only."),
    row(13, "I see the dukul-mukul lizard.", "Ngayu dukul-mukul nyajil.", "ngayu dukul-mukul nyaji-l | I dukul-mukul.lizard see-NONPAST", "r175_present_i_dukulmukul", ["ngayu", "dukul-mukul", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(14, "I see the ground lizard.", "Ngayu jirabay nyajil.", "ngayu jirabay nyaji-l | I ground.lizard see-NONPAST", "r175_present_i_jirabay", ["ngayu", "jirabay", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(15, "I see the small lizard.", "Ngayu junbirr nyajil.", "ngayu junbirr nyaji-l | I small.lizard see-NONPAST", "r175_present_i_junbirr", ["ngayu", "junbirr", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(16, "I see the striped water snake.", "Ngayu kabuljaka nyajil.", "ngayu kabuljaka nyaji-l | I striped.water.snake see-NONPAST", "r175_present_i_kabuljaka", ["ngayu", "kabuljaka", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(17, "I see the gecko.", "Ngayu kulmba-kulmba nyajil.", "ngayu kulmba-kulmba nyaji-l | I gecko see-NONPAST", "r175_present_i_kulmbakulmba", ["ngayu", "kulmba-kulmba", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(18, "I see the carpet snake.", "Ngayu kurriyala nyajil.", "ngayu kurriyala nyaji-l | I carpet.snake see-NONPAST", "r175_present_i_kurriyala", ["ngayu", "kurriyala", "nyaji-l"], "Pronoun A bare; selected reptile sense only."),
    row(19, "I see the freshwater crocodile.", "Ngayu ngawurr-ngawun nyajil.", "ngayu ngawurr-ngawun nyaji-l | I freshwater.crocodile see-NONPAST", "r175_present_i_ngawurrngawun", ["ngayu", "ngawurr-ngawun", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(20, "I see the sea snake.", "Ngayu ngumbul nyajil.", "ngayu ngumbul nyaji-l | I sea.snake see-NONPAST", "r175_present_i_ngumbul", ["ngayu", "ngumbul", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(21, "You see the fresh water snake there.", "Yundu banamu yinyay nyajil.", "yundu banamu yinyay nyaji-l | you fresh.water.snake there see-NONPAST", "r175_present_you_banamu_there", ["yundu", "banamu", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(22, "You see the light bellied black snake there.", "Yundu binju yinyay nyajil.", "yundu binju yinyay nyaji-l | you light.bellied.black.snake there see-NONPAST", "r175_present_you_binju_there", ["yundu", "binju", "yinyay", "nyaji-l"], "Second-person pronoun A bare; selected reptile sense only."),
    row(23, "You see the dukul-mukul lizard there.", "Yundu dukul-mukul yinyay nyajil.", "yundu dukul-mukul yinyay nyaji-l | you dukul-mukul.lizard there see-NONPAST", "r175_present_you_dukulmukul_there", ["yundu", "dukul-mukul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(24, "You see the ground lizard there.", "Yundu jirabay yinyay nyajil.", "yundu jirabay yinyay nyaji-l | you ground.lizard there see-NONPAST", "r175_present_you_jirabay_there", ["yundu", "jirabay", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(25, "You see the small lizard there.", "Yundu junbirr yinyay nyajil.", "yundu junbirr yinyay nyaji-l | you small.lizard there see-NONPAST", "r175_present_you_junbirr_there", ["yundu", "junbirr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the striped water snake there.", "Yundu kabuljaka yinyay nyajil.", "yundu kabuljaka yinyay nyaji-l | you striped.water.snake there see-NONPAST", "r175_present_you_kabuljaka_there", ["yundu", "kabuljaka", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the gecko there.", "Yundu kulmba-kulmba yinyay nyajil.", "yundu kulmba-kulmba yinyay nyaji-l | you gecko there see-NONPAST", "r175_present_you_kulmbakulmba_there", ["yundu", "kulmba-kulmba", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the carpet snake there.", "Yundu kurriyala yinyay nyajil.", "yundu kurriyala yinyay nyaji-l | you carpet.snake there see-NONPAST", "r175_present_you_kurriyala_there", ["yundu", "kurriyala", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(29, "You see the freshwater crocodile there.", "Yundu ngawurr-ngawun yinyay nyajil.", "yundu ngawurr-ngawun yinyay nyaji-l | you freshwater.crocodile there see-NONPAST", "r175_present_you_ngawurrngawun_there", ["yundu", "ngawurr-ngawun", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the sea snake there.", "Yundu ngumbul yinyay nyajil.", "yundu ngumbul yinyay nyaji-l | you sea.snake there see-NONPAST", "r175_present_you_ngumbul_there", ["yundu", "ngumbul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the fresh water snake there.", "Jana banamu yinyay nyajin.", "jana banamu yinyay nyaji-ny | they fresh.water.snake there see-PAST", "r175_past_they_banamu_there", ["jana", "banamu", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the light bellied black snake there.", "Jana binju yinyay nyajin.", "jana binju yinyay nyaji-ny | they light.bellied.black.snake there see-PAST", "r175_past_they_binju_there", ["jana", "binju", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; selected reptile sense only."),
    row(33, "They saw the dukul-mukul lizard there.", "Jana dukul-mukul yinyay nyajin.", "jana dukul-mukul yinyay nyaji-ny | they dukul-mukul.lizard there see-PAST", "r175_past_they_dukulmukul_there", ["jana", "dukul-mukul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(34, "They saw the ground lizard there.", "Jana jirabay yinyay nyajin.", "jana jirabay yinyay nyaji-ny | they ground.lizard there see-PAST", "r175_past_they_jirabay_there", ["jana", "jirabay", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(35, "They saw the small lizard there.", "Jana junbirr yinyay nyajin.", "jana junbirr yinyay nyaji-ny | they small.lizard there see-PAST", "r175_past_they_junbirr_there", ["jana", "junbirr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(36, "They saw the striped water snake there.", "Jana kabuljaka yinyay nyajin.", "jana kabuljaka yinyay nyaji-ny | they striped.water.snake there see-PAST", "r175_past_they_kabuljaka_there", ["jana", "kabuljaka", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(37, "They saw the gecko there.", "Jana kulmba-kulmba yinyay nyajin.", "jana kulmba-kulmba yinyay nyaji-ny | they gecko there see-PAST", "r175_past_they_kulmbakulmba_there", ["jana", "kulmba-kulmba", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(38, "They saw the carpet snake there.", "Jana kurriyala yinyay nyajin.", "jana kurriyala yinyay nyaji-ny | they carpet.snake there see-PAST", "r175_past_they_kurriyala_there", ["jana", "kurriyala", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; selected reptile sense only."),
    row(39, "They saw the freshwater crocodile there.", "Jana ngawurr-ngawun yinyay nyajin.", "jana ngawurr-ngawun yinyay nyaji-ny | they freshwater.crocodile there see-PAST", "r175_past_they_ngawurrngawun_there", ["jana", "ngawurr-ngawun", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(40, "They saw the sea snake there.", "Jana ngumbul yinyay nyajin.", "jana ngumbul yinyay nyaji-ny | they sea.snake there see-PAST", "r175_past_they_ngumbul_there", ["jana", "ngumbul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(41, "We see the fresh water snake here.", "Ngana banamu yaluy nyajil.", "ngana banamu yaluy nyaji-l | we fresh.water.snake here see-NONPAST", "r175_present_we_banamu_here", ["ngana", "banamu", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(42, "We see the light bellied black snake here.", "Ngana binju yaluy nyajil.", "ngana binju yaluy nyaji-l | we light.bellied.black.snake here see-NONPAST", "r175_present_we_binju_here", ["ngana", "binju", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; selected reptile sense only."),
    row(43, "We see the dukul-mukul lizard here.", "Ngana dukul-mukul yaluy nyajil.", "ngana dukul-mukul yaluy nyaji-l | we dukul-mukul.lizard here see-NONPAST", "r175_present_we_dukulmukul_here", ["ngana", "dukul-mukul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(44, "We see the ground lizard here.", "Ngana jirabay yaluy nyajil.", "ngana jirabay yaluy nyaji-l | we ground.lizard here see-NONPAST", "r175_present_we_jirabay_here", ["ngana", "jirabay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(45, "We see the small lizard here.", "Ngana junbirr yaluy nyajil.", "ngana junbirr yaluy nyaji-l | we small.lizard here see-NONPAST", "r175_present_we_junbirr_here", ["ngana", "junbirr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(46, "We see the striped water snake here.", "Ngana kabuljaka yaluy nyajil.", "ngana kabuljaka yaluy nyaji-l | we striped.water.snake here see-NONPAST", "r175_present_we_kabuljaka_here", ["ngana", "kabuljaka", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(47, "We see the gecko here.", "Ngana kulmba-kulmba yaluy nyajil.", "ngana kulmba-kulmba yaluy nyaji-l | we gecko here see-NONPAST", "r175_present_we_kulmbakulmba_here", ["ngana", "kulmba-kulmba", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(48, "We see the carpet snake here.", "Ngana kurriyala yaluy nyajil.", "ngana kurriyala yaluy nyaji-l | we carpet.snake here see-NONPAST", "r175_present_we_kurriyala_here", ["ngana", "kurriyala", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; selected reptile sense only."),
    row(49, "We see the freshwater crocodile here.", "Ngana ngawurr-ngawun yaluy nyajil.", "ngana ngawurr-ngawun yaluy nyaji-l | we freshwater.crocodile here see-NONPAST", "r175_present_we_ngawurrngawun_here", ["ngana", "ngawurr-ngawun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(50, "We see the sea snake here.", "Ngana ngumbul yaluy nyajil.", "ngana ngumbul yaluy nyaji-l | we sea.snake here see-NONPAST", "r175_present_we_ngumbul_here", ["ngana", "ngumbul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
]


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|mba|mbu|muny|darr|burr|bu|ka|nka|nku|ji|jirr|ku|mundu|amu|mu|iji|nda|ndu|anda|undu|unji|nji|kari|baka)\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)}\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("r175_"):
            issues.append(f"{label}: Rule 175 frame must start with r175_")
        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 175")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied rejected/use 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 175 target head, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected.replace(" ", ".") not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yaluy") or "yaluy" not in words or "here" not in english_low:
                issues.append(f"{label}: Rule 175 deictic rows require yaluy/here")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 175 perception rows must use nyaji-l")
            first = first_word(low)
            if first not in PRONOUN_A:
                issues.append(f"{label}: perception A should be an approved bare pronoun")
            if 11 <= seq <= 20 and first != "ngayu":
                issues.append(f"{label}: rows 11-20 require ngayu")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yinyay/there")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yinyay") or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yinyay + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yaluy/here")
            if "nyajin" in low and "see-PAST" not in analysis:
                issues.append(f"{label}: nyajin must be glossed as see-PAST")
            if "nyajil" in low and "see-NONPAST" not in analysis:
                issues.append(f"{label}: nyajil must be glossed as see-NONPAST")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied reptile event/use/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 175 draft: reptile reference lexical expansion after Rule 174", "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

    record_event(db, batch_label=LABEL, phase="source", event_type="source-pass", actor="claude-main",
                 detail="Rule 175 source pass selected ten unused reptile-reference heads: banamu, binju, dukul-mukul, jirabay, junbirr, kabuljaka, kulmba-kulmba, kurriyala, ngawurr-ngawun, and ngumbul. Dictionary exact readback confirmed selected senses. Grammar readback found junbirr, kurriyala, and ngawurr-ngawun attestations but no target-head conflict; kurriyala story, source-ablative, and run-away examples remain closed. Patz readback reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Boundary-aware corpus readback found zero accepted/revised/under_review rows for selected targets.",
                 command="structured dictionary readback; rg grammar readback; sqlite boundary-aware corpus 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 175 is a lexical reptile-reference pass for ten bare target heads. It excludes wrong-marriage, cooking, poisonous, fish/grunter, belt, running-from, story, story-site, legend, mythological-person, food, edible, eating, hunting, catching, chase, firestick, eye/fighter, place, river, egg, body-part, target case, target compounds, possession, and event claims.",
                 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/under_review cross-corpus duplicates.",
                 command="sqlite exact lower(trim(kuku)) duplicate scan before banking", artifact_path="batch_scripts/bank_217.py", created_at=NOW)
    record_event(db, batch_label=LABEL, phase="preflight", event_type="static-guard-pass", actor="claude-main",
                 detail="Static guards passed: exactly one Rule 175 reptile target per row; all targets bare; no loans; no rejected-reptile/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_217.py static scan", artifact_path="batch_scripts/bank_217.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, *row_data[:9], "under_review", row_data[9], "claude-main", NOW, NOW) for row_data in ROWS],
    )
    db.commit()

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


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