#!/usr/bin/env python3
"""Bank batch-215: Rule 173 bird reference lexical expansion after Rule 172."""

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

TARGET_HEADS = {
    "barbarr": "young cassowary",
    "bayil-bayil": "mudlark",
    "biluwarra": "spoon bill bird",
    "binjul-binjul": "scarlet robin",
    "dijarr-dijin": "willie wagtail",
    "kurburrubun": "magpie",
    "kurkumbay": "butcherbird",
    "kurungka": "bronze wing pigeon",
    "munwingkul": "dove",
    "yindili": "forest kingfisher",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "babarr", "bujarr-bujarr", "dukunjuju", "kujuway", "yiki", "birmba", "dabway", "dakwul-dakwul",
    "dakwurr-dakwun", "dirrmbay", "kurrujuwa", "mirrku", "mulumu", "ngurrku", "walu-dalbaji",
    "wandi", "yalngkurr", "buyi", "nangki", "diburr", "dawa-dawa", "jamarbina", "nili-nili",
    "mabal", "kulbal", "kurranji", "dikal", "juku-juku", "kuludu", "juril-juril",
}
DENY_ENGLISH = (
    "fly", "flies", "flying", "flew", "flight", "sing", "sings", "singing", "call", "calls", "calling",
    "dance", "dances", "dancing", "warning", "warn", "warns", "totem", "moiety", "sacred", "story",
    "story-site", "place", "place-name", "nest", "nests", "egg", "eggs", "feather", "feathers", "food",
    "eat", "eats", "ate", "eaten", "hunt", "hunting", "catch", "catches", "caught", "storm", "weather",
    "wood", "tree", "spirit", "messenger",
)


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 young cassowary is here.", "Barbarr yaluy.", "barbarr yaluy | young.cassowary here", "r173_deictic_barbarr_here", ["barbarr", "yaluy"], "Rule 173 admits barbarr as young cassowary; bird reference only."),
    row(2, "The mudlark is here.", "Bayil-bayil yaluy.", "bayil-bayil yaluy | mudlark here", "r173_deictic_bayilbayil_here", ["bayil-bayil", "yaluy"], "Rule 173 admits bayil-bayil as mudlark; reduplicated lexical head."),
    row(3, "The spoon bill bird is here.", "Biluwarra yaluy.", "biluwarra yaluy | spoon.bill.bird here", "r173_deictic_biluwarra_here", ["biluwarra", "yaluy"], "Rule 173 admits biluwarra as spoon bill bird; reference only."),
    row(4, "The scarlet robin is here.", "Binjul-binjul yaluy.", "binjul-binjul yaluy | scarlet.robin here", "r173_deictic_binjulbinjul_here", ["binjul-binjul", "yaluy"], "Rule 173 admits binjul-binjul as scarlet robin; duplicate dictionary entries agree."),
    row(5, "The willie wagtail is here.", "Dijarr-dijin yaluy.", "dijarr-dijin yaluy | willie.wagtail here", "r173_deictic_dijarrdijin_here", ["dijarr-dijin", "yaluy"], "Rule 173 admits dijarr-dijin as willie wagtail; partial reduplicated head."),
    row(6, "The magpie is here.", "Kurburrubun yaluy.", "kurburrubun yaluy | magpie here", "r173_deictic_kurburrubun_here", ["kurburrubun", "yaluy"], "Rule 173 admits kurburrubun as magpie; reference only."),
    row(7, "The butcherbird is here.", "Kurkumbay yaluy.", "kurkumbay yaluy | butcherbird here", "r173_deictic_kurkumbay_here", ["kurkumbay", "yaluy"], "Rule 173 admits kurkumbay as butcherbird; reference only."),
    row(8, "The bronze wing pigeon is here.", "Kurungka yaluy.", "kurungka yaluy | bronze.wing.pigeon here", "r173_deictic_kurungka_here", ["kurungka", "yaluy"], "Rule 173 admits kurungka as bronze wing pigeon; the common-name wing is not a body-part claim."),
    row(9, "The dove is here.", "Munwingkul yaluy.", "munwingkul yaluy | dove here", "r173_deictic_munwingkul_here", ["munwingkul", "yaluy"], "Rule 173 admits munwingkul as dove; duplicate dictionary entries agree on dove."),
    row(10, "The forest kingfisher is here.", "Yindili yaluy.", "yindili yaluy | forest.kingfisher here", "r173_deictic_yindili_here", ["yindili", "yaluy"], "Rule 173 admits yindili as forest kingfisher; duplicate dictionary entries agree."),
    row(11, "I see the young cassowary.", "Ngayu barbarr nyajil.", "ngayu barbarr nyaji-l | I young.cassowary see-NONPAST", "r173_present_i_barbarr", ["ngayu", "barbarr", "nyaji-l"], "Pronoun A bare; barbarr object bare."),
    row(12, "I see the mudlark.", "Ngayu bayil-bayil nyajil.", "ngayu bayil-bayil nyaji-l | I mudlark see-NONPAST", "r173_present_i_bayilbayil", ["ngayu", "bayil-bayil", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(13, "I see the spoon bill bird.", "Ngayu biluwarra nyajil.", "ngayu biluwarra nyaji-l | I spoon.bill.bird see-NONPAST", "r173_present_i_biluwarra", ["ngayu", "biluwarra", "nyaji-l"], "Pronoun A bare; biluwarra object bare."),
    row(14, "I see the scarlet robin.", "Ngayu binjul-binjul nyajil.", "ngayu binjul-binjul nyaji-l | I scarlet.robin see-NONPAST", "r173_present_i_binjulbinjul", ["ngayu", "binjul-binjul", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(15, "I see the willie wagtail.", "Ngayu dijarr-dijin nyajil.", "ngayu dijarr-dijin nyaji-l | I willie.wagtail see-NONPAST", "r173_present_i_dijarrdijin", ["ngayu", "dijarr-dijin", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(16, "I see the magpie.", "Ngayu kurburrubun nyajil.", "ngayu kurburrubun nyaji-l | I magpie see-NONPAST", "r173_present_i_kurburrubun", ["ngayu", "kurburrubun", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(17, "I see the butcherbird.", "Ngayu kurkumbay nyajil.", "ngayu kurkumbay nyaji-l | I butcherbird see-NONPAST", "r173_present_i_kurkumbay", ["ngayu", "kurkumbay", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(18, "I see the bronze wing pigeon.", "Ngayu kurungka nyajil.", "ngayu kurungka nyaji-l | I bronze.wing.pigeon see-NONPAST", "r173_present_i_kurungka", ["ngayu", "kurungka", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(19, "I see the dove.", "Ngayu munwingkul nyajil.", "ngayu munwingkul nyaji-l | I dove see-NONPAST", "r173_present_i_munwingkul", ["ngayu", "munwingkul", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(20, "I see the forest kingfisher.", "Ngayu yindili nyajil.", "ngayu yindili nyaji-l | I forest.kingfisher see-NONPAST", "r173_present_i_yindili", ["ngayu", "yindili", "nyaji-l"], "Pronoun A bare; target object bare."),
    row(21, "You see the young cassowary there.", "Yundu barbarr yinyay nyajil.", "yundu barbarr yinyay nyaji-l | you young.cassowary there see-NONPAST", "r173_present_you_barbarr_there", ["yundu", "barbarr", "yinyay", "nyaji-l"], "Second-person pronoun A bare; yinyay support only."),
    row(22, "You see the mudlark there.", "Yundu bayil-bayil yinyay nyajil.", "yundu bayil-bayil yinyay nyaji-l | you mudlark there see-NONPAST", "r173_present_you_bayilbayil_there", ["yundu", "bayil-bayil", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(23, "You see the spoon bill bird there.", "Yundu biluwarra yinyay nyajil.", "yundu biluwarra yinyay nyaji-l | you spoon.bill.bird there see-NONPAST", "r173_present_you_biluwarra_there", ["yundu", "biluwarra", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(24, "You see the scarlet robin there.", "Yundu binjul-binjul yinyay nyajil.", "yundu binjul-binjul yinyay nyaji-l | you scarlet.robin there see-NONPAST", "r173_present_you_binjulbinjul_there", ["yundu", "binjul-binjul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(25, "You see the willie wagtail there.", "Yundu dijarr-dijin yinyay nyajil.", "yundu dijarr-dijin yinyay nyaji-l | you willie.wagtail there see-NONPAST", "r173_present_you_dijarrdijin_there", ["yundu", "dijarr-dijin", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the magpie there.", "Yundu kurburrubun yinyay nyajil.", "yundu kurburrubun yinyay nyaji-l | you magpie there see-NONPAST", "r173_present_you_kurburrubun_there", ["yundu", "kurburrubun", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the butcherbird there.", "Yundu kurkumbay yinyay nyajil.", "yundu kurkumbay yinyay nyaji-l | you butcherbird there see-NONPAST", "r173_present_you_kurkumbay_there", ["yundu", "kurkumbay", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the bronze wing pigeon there.", "Yundu kurungka yinyay nyajil.", "yundu kurungka yinyay nyaji-l | you bronze.wing.pigeon there see-NONPAST", "r173_present_you_kurungka_there", ["yundu", "kurungka", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(29, "You see the dove there.", "Yundu munwingkul yinyay nyajil.", "yundu munwingkul yinyay nyaji-l | you dove there see-NONPAST", "r173_present_you_munwingkul_there", ["yundu", "munwingkul", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the forest kingfisher there.", "Yundu yindili yinyay nyajil.", "yundu yindili yinyay nyaji-l | you forest.kingfisher there see-NONPAST", "r173_present_you_yindili_there", ["yundu", "yindili", "yinyay", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the young cassowary there.", "Jana barbarr yinyay nyajin.", "jana barbarr yinyay nyaji-ny | they young.cassowary there see-PAST", "r173_past_they_barbarr_there", ["jana", "barbarr", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; past perception."),
    row(32, "They saw the mudlark there.", "Jana bayil-bayil yinyay nyajin.", "jana bayil-bayil yinyay nyaji-ny | they mudlark there see-PAST", "r173_past_they_bayilbayil_there", ["jana", "bayil-bayil", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(33, "They saw the spoon bill bird there.", "Jana biluwarra yinyay nyajin.", "jana biluwarra yinyay nyaji-ny | they spoon.bill.bird there see-PAST", "r173_past_they_biluwarra_there", ["jana", "biluwarra", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(34, "They saw the scarlet robin there.", "Jana binjul-binjul yinyay nyajin.", "jana binjul-binjul yinyay nyaji-ny | they scarlet.robin there see-PAST", "r173_past_they_binjulbinjul_there", ["jana", "binjul-binjul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(35, "They saw the willie wagtail there.", "Jana dijarr-dijin yinyay nyajin.", "jana dijarr-dijin yinyay nyaji-ny | they willie.wagtail there see-PAST", "r173_past_they_dijarrdijin_there", ["jana", "dijarr-dijin", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(36, "They saw the magpie there.", "Jana kurburrubun yinyay nyajin.", "jana kurburrubun yinyay nyaji-ny | they magpie there see-PAST", "r173_past_they_kurburrubun_there", ["jana", "kurburrubun", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(37, "They saw the butcherbird there.", "Jana kurkumbay yinyay nyajin.", "jana kurkumbay yinyay nyaji-ny | they butcherbird there see-PAST", "r173_past_they_kurkumbay_there", ["jana", "kurkumbay", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(38, "They saw the bronze wing pigeon there.", "Jana kurungka yinyay nyajin.", "jana kurungka yinyay nyaji-ny | they bronze.wing.pigeon there see-PAST", "r173_past_they_kurungka_there", ["jana", "kurungka", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(39, "They saw the dove there.", "Jana munwingkul yinyay nyajin.", "jana munwingkul yinyay nyaji-ny | they dove there see-PAST", "r173_past_they_munwingkul_there", ["jana", "munwingkul", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(40, "They saw the forest kingfisher there.", "Jana yindili yinyay nyajin.", "jana yindili yinyay nyaji-ny | they forest.kingfisher there see-PAST", "r173_past_they_yindili_there", ["jana", "yindili", "yinyay", "nyaji-l"], "Third-person plural pronoun A bare; target bare."),
    row(41, "We see the young cassowary here.", "Ngana barbarr yaluy nyajil.", "ngana barbarr yaluy nyaji-l | we young.cassowary here see-NONPAST", "r173_present_we_barbarr_here", ["ngana", "barbarr", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; yaluy support only."),
    row(42, "We see the mudlark here.", "Ngana bayil-bayil yaluy nyajil.", "ngana bayil-bayil yaluy nyaji-l | we mudlark here see-NONPAST", "r173_present_we_bayilbayil_here", ["ngana", "bayil-bayil", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(43, "We see the spoon bill bird here.", "Ngana biluwarra yaluy nyajil.", "ngana biluwarra yaluy nyaji-l | we spoon.bill.bird here see-NONPAST", "r173_present_we_biluwarra_here", ["ngana", "biluwarra", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(44, "We see the scarlet robin here.", "Ngana binjul-binjul yaluy nyajil.", "ngana binjul-binjul yaluy nyaji-l | we scarlet.robin here see-NONPAST", "r173_present_we_binjulbinjul_here", ["ngana", "binjul-binjul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(45, "We see the willie wagtail here.", "Ngana dijarr-dijin yaluy nyajil.", "ngana dijarr-dijin yaluy nyaji-l | we willie.wagtail here see-NONPAST", "r173_present_we_dijarrdijin_here", ["ngana", "dijarr-dijin", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(46, "We see the magpie here.", "Ngana kurburrubun yaluy nyajil.", "ngana kurburrubun yaluy nyaji-l | we magpie here see-NONPAST", "r173_present_we_kurburrubun_here", ["ngana", "kurburrubun", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(47, "We see the butcherbird here.", "Ngana kurkumbay yaluy nyajil.", "ngana kurkumbay yaluy nyaji-l | we butcherbird here see-NONPAST", "r173_present_we_kurkumbay_here", ["ngana", "kurkumbay", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(48, "We see the bronze wing pigeon here.", "Ngana kurungka yaluy nyajil.", "ngana kurungka yaluy nyaji-l | we bronze.wing.pigeon here see-NONPAST", "r173_present_we_kurungka_here", ["ngana", "kurungka", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(49, "We see the dove here.", "Ngana munwingkul yaluy nyajil.", "ngana munwingkul yaluy nyaji-l | we dove here see-NONPAST", "r173_present_we_munwingkul_here", ["ngana", "munwingkul", "yaluy", "nyaji-l"], "Inclusive pronoun A bare; target bare."),
    row(50, "We see the forest kingfisher here.", "Ngana yindili yaluy nyajil.", "ngana yindili yaluy nyaji-l | we forest.kingfisher here see-NONPAST", "r173_present_we_yindili_here", ["ngana", "yindili", "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("r173_"):
            issues.append(f"{label}: Rule 173 frame must start with r173_")
        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 173")
        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 173 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 and selected 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 173 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 173 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 bird 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 173 draft: bird reference lexical expansion after Rule 172", "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 173 source pass selected ten unused bird reference heads: barbarr, bayil-bayil, biluwarra, binjul-binjul, dijarr-dijin, kurburrubun, kurkumbay, kurungka, munwingkul, and yindili. Dictionary exact readback confirmed selected senses. Patz readback found no target-head conflicts and 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 173 is a lexical bird-reference pass for ten bare target heads. It excludes flying, singing, calling, dancing, warning, totem/moiety, sacred-bird, story-site, nest, egg, feather, food, eating, hunting, catching, storm, place, wood, secondary-sense, 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_215.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 173 bird target per row; all targets bare; no loans; no rejected-bird/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_215.py static scan", artifact_path="batch_scripts/bank_215.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())
