#!/usr/bin/env python3
"""Bank batch-210: Rule 168 construction consolidation after Rule 167."""

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-210"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-210-construction-consolidation-after-rule167-process.md"

TARGET_HEADS = {
    "jina-jina": "water gum tree",
    "jarrangkal": "fig tree",
    "julbin": "scrub tree",
    "kunjarri": "palm",
    "kurruy": "plum tree",
    "malurri": "fern tree",
    "mawar": "vine",
    "maya": "vine",
    "wangay": "vine",
    "yawarr": "palm",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "mayi", "nuka", "nukan", "waju", "wajun", "warrmba", "warrmban", "mani", "manin", "daji", "dajin",
    "dinda", "dindan", "duda", "dudan", "wukurri", "wukurrin", "ngara", "ngaran", "kuni", "kunin",
    "yaka", "yakan", "balka", "balkan", "kida", "kidan", "dunga", "dungan", "wandi", "wandin",
    "baya", "kubu", "kurrma", "medicine", "juku", "bark", "spear", "storm", "bayan", "bubu",
    "buyku", "bijan", "dukal", "dakumbar", "jinjay", "jalnji", "ngakun", "ngunyin", "kaja", "kajal",
    "munja", "munjan", "jaba", "jaban", "kulba", "kulban", "wabu", "woomera",
}
DENY_ENGLISH = (
    "eat", "eats", "ate", "eaten", "edible", "food", "fruit", "nut", "medicine", "heal", "healed",
    "sore", "bark", "burn", "burned", "burnt", "fire", "smoke", "storm", "spear", "woomera", "timber",
    "wood", "stick", "weave", "woven", "tie", "tied", "string", "brace", "braces", "basket", "container",
    "cook", "cooked", "cooking", "roast", "roasted", "place", "camp", "main camp", "beach", "gather",
    "gathered", "harvest", "harvested", "dig", "dug", "pod", "pods", "seed", "seeds",
)


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 water gum tree is there.", "Jina-jina yinyay.", "jina-jina yinyay | water.gum.tree there", "r168_deictic_jinajina_there", ["jina-jina", "yinyay"], "Rule 168 retains Rule 167 jina-jina as Yalanji water gum tree; bare yinyay deictic consolidation."),
    row(2, "The fig tree is there.", "Jarrangkal yinyay.", "jarrangkal yinyay | fig.tree there", "r168_deictic_jarrangkal_there", ["jarrangkal", "yinyay"], "Rule 168 retains Rule 167 jarrangkal as fig tree; no fruit/food row."),
    row(3, "The scrub tree is there.", "Julbin yinyay.", "julbin yinyay | scrub.tree there", "r168_deictic_julbin_there", ["julbin", "yinyay"], "Rule 168 retains Rule 167 julbin as scrub tree; no edible-processing row."),
    row(4, "The kunjarri palm is there.", "Kunjarri yinyay.", "kunjarri yinyay | palm there", "r168_deictic_kunjarri_there", ["kunjarri", "yinyay"], "Rule 168 retains Rule 167 kunjarri as palm; no bark/container/edible row."),
    row(5, "The plum tree is there.", "Kurruy yinyay.", "kurruy yinyay | plum.tree there", "r168_deictic_kurruy_there", ["kurruy", "yinyay"], "Rule 168 retains Rule 167 kurruy as plum tree; no fruit/food row."),
    row(6, "The fern tree is there.", "Malurri yinyay.", "malurri yinyay | fern.tree there", "r168_deictic_malurri_there", ["malurri", "yinyay"], "Rule 168 retains Rule 167 malurri as fern tree."),
    row(7, "The mawar vine is there.", "Mawar yinyay.", "mawar yinyay | vine there", "r168_deictic_mawar_there", ["mawar", "yinyay"], "Rule 168 retains Rule 167 mawar as vine; no braces/tying/string row."),
    row(8, "The maya vine is there.", "Maya yinyay.", "maya yinyay | vine there", "r168_deictic_maya_there", ["maya", "yinyay"], "Rule 168 retains Rule 167 maya as vine/clinging plant; reference only."),
    row(9, "The wangay vine is there.", "Wangay yinyay.", "wangay yinyay | vine there", "r168_deictic_wangay_there", ["wangay", "yinyay"], "Rule 168 retains Rule 167 wangay as vine; no fruit/place row."),
    row(10, "The yawarr palm is there.", "Yawarr yinyay.", "yawarr yinyay | palm there", "r168_deictic_yawarr_there", ["yawarr", "yinyay"], "Rule 168 retains Rule 167 yawarr as palm."),
    row(11, "I see the water gum tree here.", "Ngayu jina-jina yaluy nyajil.", "ngayu jina-jina yaluy nyaji-l | I water.gum.tree here see-NONPAST", "r168_present_i_jinajina_here", ["ngayu", "jina-jina", "yaluy", "nyaji-l"], "Pronoun A bare; jina-jina object bare; yaluy support only."),
    row(12, "I see the fig tree here.", "Ngayu jarrangkal yaluy nyajil.", "ngayu jarrangkal yaluy nyaji-l | I fig.tree here see-NONPAST", "r168_present_i_jarrangkal_here", ["ngayu", "jarrangkal", "yaluy", "nyaji-l"], "Pronoun A bare; jarrangkal object bare; no fruit/food row."),
    row(13, "I see the scrub tree here.", "Ngayu julbin yaluy nyajil.", "ngayu julbin yaluy nyaji-l | I scrub.tree here see-NONPAST", "r168_present_i_julbin_here", ["ngayu", "julbin", "yaluy", "nyaji-l"], "Pronoun A bare; julbin object bare; no edible-processing row."),
    row(14, "I see the kunjarri palm here.", "Ngayu kunjarri yaluy nyajil.", "ngayu kunjarri yaluy nyaji-l | I palm here see-NONPAST", "r168_present_i_kunjarri_here", ["ngayu", "kunjarri", "yaluy", "nyaji-l"], "Pronoun A bare; kunjarri object bare; no bark/container/edible row."),
    row(15, "I see the plum tree here.", "Ngayu kurruy yaluy nyajil.", "ngayu kurruy yaluy nyaji-l | I plum.tree here see-NONPAST", "r168_present_i_kurruy_here", ["ngayu", "kurruy", "yaluy", "nyaji-l"], "Pronoun A bare; kurruy object bare; no fruit/food row."),
    row(16, "I see the fern tree here.", "Ngayu malurri yaluy nyajil.", "ngayu malurri yaluy nyaji-l | I fern.tree here see-NONPAST", "r168_present_i_malurri_here", ["ngayu", "malurri", "yaluy", "nyaji-l"], "Pronoun A bare; malurri object bare."),
    row(17, "I see the mawar vine here.", "Ngayu mawar yaluy nyajil.", "ngayu mawar yaluy nyaji-l | I vine here see-NONPAST", "r168_present_i_mawar_here", ["ngayu", "mawar", "yaluy", "nyaji-l"], "Pronoun A bare; mawar object bare; no tying/string row."),
    row(18, "I see the maya vine here.", "Ngayu maya yaluy nyajil.", "ngayu maya yaluy nyaji-l | I vine here see-NONPAST", "r168_present_i_maya_here", ["ngayu", "maya", "yaluy", "nyaji-l"], "Pronoun A bare; maya object bare."),
    row(19, "I see the wangay vine here.", "Ngayu wangay yaluy nyajil.", "ngayu wangay yaluy nyaji-l | I vine here see-NONPAST", "r168_present_i_wangay_here", ["ngayu", "wangay", "yaluy", "nyaji-l"], "Pronoun A bare; wangay object bare; no fruit/place row."),
    row(20, "I see the yawarr palm here.", "Ngayu yawarr yaluy nyajil.", "ngayu yawarr yaluy nyaji-l | I palm here see-NONPAST", "r168_present_i_yawarr_here", ["ngayu", "yawarr", "yaluy", "nyaji-l"], "Pronoun A bare; yawarr object bare."),
    row(21, "You see the water gum tree here.", "Yundu jina-jina yaluy nyajil.", "yundu jina-jina yaluy nyaji-l | you water.gum.tree here see-NONPAST", "r168_present_you_jinajina_here", ["yundu", "jina-jina", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support only; no timber/woomera row."),
    row(22, "You see the fig tree here.", "Yundu jarrangkal yaluy nyajil.", "yundu jarrangkal yaluy nyaji-l | you fig.tree here see-NONPAST", "r168_present_you_jarrangkal_here", ["yundu", "jarrangkal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no fruit/food row."),
    row(23, "You see the scrub tree here.", "Yundu julbin yaluy nyajil.", "yundu julbin yaluy nyaji-l | you scrub.tree here see-NONPAST", "r168_present_you_julbin_here", ["yundu", "julbin", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no edible-processing row."),
    row(24, "You see the kunjarri palm here.", "Yundu kunjarri yaluy nyajil.", "yundu kunjarri yaluy nyaji-l | you palm here see-NONPAST", "r168_present_you_kunjarri_here", ["yundu", "kunjarri", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no bark/container/edible row."),
    row(25, "You see the plum tree here.", "Yundu kurruy yaluy nyajil.", "yundu kurruy yaluy nyaji-l | you plum.tree here see-NONPAST", "r168_present_you_kurruy_here", ["yundu", "kurruy", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no fruit/food row."),
    row(26, "You see the fern tree here.", "Yundu malurri yaluy nyajil.", "yundu malurri yaluy nyaji-l | you fern.tree here see-NONPAST", "r168_present_you_malurri_here", ["yundu", "malurri", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(27, "You see the mawar vine here.", "Yundu mawar yaluy nyajil.", "yundu mawar yaluy nyaji-l | you vine here see-NONPAST", "r168_present_you_mawar_here", ["yundu", "mawar", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no tying/string row."),
    row(28, "You see the maya vine here.", "Yundu maya yaluy nyajil.", "yundu maya yaluy nyaji-l | you vine here see-NONPAST", "r168_present_you_maya_here", ["yundu", "maya", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(29, "You see the wangay vine here.", "Yundu wangay yaluy nyajil.", "yundu wangay yaluy nyaji-l | you vine here see-NONPAST", "r168_present_you_wangay_here", ["yundu", "wangay", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no fruit/place row."),
    row(30, "You see the yawarr palm here.", "Yundu yawarr yaluy nyajil.", "yundu yawarr yaluy nyaji-l | you palm here see-NONPAST", "r168_present_you_yawarr_here", ["yundu", "yawarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(31, "They saw the water gum tree here.", "Jana jina-jina yaluy nyajin.", "jana jina-jina yaluy nyaji-ny | they water.gum.tree here see-PAST", "r168_past_they_jinajina_here", ["jana", "jina-jina", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception; yaluy support only."),
    row(32, "They saw the fig tree here.", "Jana jarrangkal yaluy nyajin.", "jana jarrangkal yaluy nyaji-ny | they fig.tree here see-PAST", "r168_past_they_jarrangkal_here", ["jana", "jarrangkal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/food row."),
    row(33, "They saw the scrub tree here.", "Jana julbin yaluy nyajin.", "jana julbin yaluy nyaji-ny | they scrub.tree here see-PAST", "r168_past_they_julbin_here", ["jana", "julbin", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no edible-processing row."),
    row(34, "They saw the kunjarri palm here.", "Jana kunjarri yaluy nyajin.", "jana kunjarri yaluy nyaji-ny | they palm here see-PAST", "r168_past_they_kunjarri_here", ["jana", "kunjarri", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no bark/container/edible row."),
    row(35, "They saw the plum tree here.", "Jana kurruy yaluy nyajin.", "jana kurruy yaluy nyaji-ny | they plum.tree here see-PAST", "r168_past_they_kurruy_here", ["jana", "kurruy", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/food row."),
    row(36, "They saw the fern tree here.", "Jana malurri yaluy nyajin.", "jana malurri yaluy nyaji-ny | they fern.tree here see-PAST", "r168_past_they_malurri_here", ["jana", "malurri", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(37, "They saw the mawar vine here.", "Jana mawar yaluy nyajin.", "jana mawar yaluy nyaji-ny | they vine here see-PAST", "r168_past_they_mawar_here", ["jana", "mawar", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no tying/string row."),
    row(38, "They saw the maya vine here.", "Jana maya yaluy nyajin.", "jana maya yaluy nyaji-ny | they vine here see-PAST", "r168_past_they_maya_here", ["jana", "maya", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(39, "They saw the wangay vine here.", "Jana wangay yaluy nyajin.", "jana wangay yaluy nyaji-ny | they vine here see-PAST", "r168_past_they_wangay_here", ["jana", "wangay", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no fruit/place row."),
    row(40, "They saw the yawarr palm here.", "Jana yawarr yaluy nyajin.", "jana yawarr yaluy nyaji-ny | they palm here see-PAST", "r168_past_they_yawarr_here", ["jana", "yawarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(41, "We see the water gum tree there.", "Ngana jina-jina yinyay nyajil.", "ngana jina-jina yinyay nyaji-l | we water.gum.tree there see-NONPAST", "r168_present_we_jinajina_there", ["ngana", "jina-jina", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support only; no timber/woomera row."),
    row(42, "We see the fig tree there.", "Ngana jarrangkal yinyay nyajil.", "ngana jarrangkal yinyay nyaji-l | we fig.tree there see-NONPAST", "r168_present_we_jarrangkal_there", ["ngana", "jarrangkal", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no fruit/food row."),
    row(43, "We see the scrub tree there.", "Ngana julbin yinyay nyajil.", "ngana julbin yinyay nyaji-l | we scrub.tree there see-NONPAST", "r168_present_we_julbin_there", ["ngana", "julbin", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no edible-processing row."),
    row(44, "We see the kunjarri palm there.", "Ngana kunjarri yinyay nyajil.", "ngana kunjarri yinyay nyaji-l | we palm there see-NONPAST", "r168_present_we_kunjarri_there", ["ngana", "kunjarri", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no bark/container/edible row."),
    row(45, "We see the plum tree there.", "Ngana kurruy yinyay nyajil.", "ngana kurruy yinyay nyaji-l | we plum.tree there see-NONPAST", "r168_present_we_kurruy_there", ["ngana", "kurruy", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no fruit/food row."),
    row(46, "We see the fern tree there.", "Ngana malurri yinyay nyajil.", "ngana malurri yinyay nyaji-l | we fern.tree there see-NONPAST", "r168_present_we_malurri_there", ["ngana", "malurri", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(47, "We see the mawar vine there.", "Ngana mawar yinyay nyajil.", "ngana mawar yinyay nyaji-l | we vine there see-NONPAST", "r168_present_we_mawar_there", ["ngana", "mawar", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no tying/string row."),
    row(48, "We see the maya vine there.", "Ngana maya yinyay nyajil.", "ngana maya yinyay nyaji-l | we vine there see-NONPAST", "r168_present_we_maya_there", ["ngana", "maya", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(49, "We see the wangay vine there.", "Ngana wangay yinyay nyajil.", "ngana wangay yinyay nyaji-l | we vine there see-NONPAST", "r168_present_we_wangay_there", ["ngana", "wangay", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no fruit/place row."),
    row(50, "We see the yawarr palm there.", "Ngana yawarr yinyay nyajil.", "ngana yawarr yinyay nyaji-l | we palm there see-NONPAST", "r168_present_we_yawarr_there", ["ngana", "yawarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object 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("r168_"):
            issues.append(f"{label}: Rule 168 frame must start with r168_")
        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 168")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied use/homograph 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 168 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, "yinyay") or "yinyay" not in words or "there" not in english_low:
                issues.append(f"{label}: Rule 168 deictic rows require yinyay/there")
        else:
            if ("nyajin" not in low and "nyajil" not in low) or "nyaji-l" not in words:
                issues.append(f"{label}: Rule 168 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" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 11-20 require ngayu + yaluy/here")
            if 21 <= seq <= 30 and (first != "yundu" or not has_token(low, "yaluy") or "here" not in english_low):
                issues.append(f"{label}: rows 21-30 require yundu + yaluy/here")
            if 31 <= seq <= 40 and (first != "jana" or not has_token(low, "yaluy") or "here" not in english_low or "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yaluy/here + past saw")
            if 41 <= seq <= 50 and (first != "ngana" or not has_token(low, "yinyay") or "there" not in english_low):
                issues.append(f"{label}: rows 41-50 require ngana + yinyay/there")
            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 use/event/homograph 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 168 draft: construction consolidation after Rule 167", "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 168 source pass retained the Rule 167 flora heads jina-jina, jarrangkal, julbin, kunjarri, kurruy, malurri, mawar, maya, wangay, and yawarr. Dictionary exact readback reconfirmed selected senses and trap prose. Patz readback reconfirmed support forms yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Boundary-aware corpus readback separated clean Rule 167 reference/perception rows from older use, food, material, place, and event rows.",
                 command="rg dictionary exact 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="construction-scope", actor="claude-main",
                 detail="Rule 168 is construction consolidation over the Rule 167 flora-reference set. It uses bare target heads only and rotates yinyay/yaluy support across deictic and perception frames. It excludes food-processing, fruit, edible-use, medicine, bark use, container-making, spear-making, timber/wood/woomera/material-source, weaving, tying, string/braces, cutting, burning, place-name, target case, target compounds, possession, and ecological-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_210.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 168 flora target per row; all targets bare; no loans; no use/event/homograph tokens; no target case/compound forms; yinyay deictic rows; yaluy-supported ngayu/yundu/jana perception rows; yinyay-supported ngana perception rows.",
                 command="python3 batch_scripts/bank_210.py static scan", artifact_path="batch_scripts/bank_210.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())
