#!/usr/bin/env python3
"""Bank batch-206: Rule 164 construction consolidation after Rule 163."""

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

TARGET_HEADS = {
    "buyukal": "buyukal tree",
    "dalkan": "casuarina pine",
    "dari": "boxwood tree",
    "dibul": "cane",
    "dilbal": "hickory tree",
    "dili": "corkwood pine",
    "jabarr": "baldy gum tree",
    "jakari": "spiderlily",
    "jama": "jama tree",
    "jilbar": "corkwood tree",
}
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",
}
DENY_ENGLISH = (
    "eat", "eats", "ate", "eaten", "food", "fruit", "nut", "medicine", "heal", "healed", "sore",
    "bark", "burn", "burned", "burnt", "fire", "smoke", "storm", "spear", "woomera", "timber",
    "wood", "stick", "weave", "woven", "tie", "tied", "basket", "place", "camp", "beach", "fruit",
    "gather", "gathered", "harvest", "harvested", "dig", "dug", "cook", "cooked", "roast", "roasted",
)


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 buyukal tree is there.", "Buyukal yinyay.", "buyukal yinyay | buyukal.tree there", "r164_deictic_buyukal_there", ["buyukal", "yinyay"], "Rule 164 retains dictionary-attested buyukal as a tree with English name unknown; bare yinyay deictic frame."),
    row(2, "The casuarina pine is there.", "Dalkan yinyay.", "dalkan yinyay | casuarina.pine there", "r164_deictic_dalkan_there", ["dalkan", "yinyay"], "Rule 164 retains dalkan as casuarina pine/beach tree; target remains bare and English avoids beach-use semantics."),
    row(3, "The boxwood tree is there.", "Dari yinyay.", "dari yinyay | boxwood.tree there", "r164_deictic_dari_there", ["dari", "yinyay"], "Rule 164 retains dictionary-attested dari boxwood tree; no high-place ecology claim."),
    row(4, "The cane is there.", "Dibul yinyay.", "dibul yinyay | cane there", "r164_deictic_dibul_there", ["dibul", "yinyay"], "Rule 164 retains dictionary-attested dibul cane; no material-use claim."),
    row(5, "The hickory tree is there.", "Dilbal yinyay.", "dilbal yinyay | hickory.tree there", "r164_deictic_dilbal_there", ["dilbal", "yinyay"], "Rule 164 retains dictionary-attested dilbal hickory tree; bare yinyay deictic frame."),
    row(6, "The corkwood pine is there.", "Dili yinyay.", "dili yinyay | corkwood.pine there", "r164_deictic_dili_there", ["dili", "yinyay"], "Rule 164 retains dili corkwood pine; Patz case table confirms bare dili but no locative target is used."),
    row(7, "The baldy gum tree is there.", "Jabarr yinyay.", "jabarr yinyay | baldy.gum.tree there", "r164_deictic_jabarr_there", ["jabarr", "yinyay"], "Rule 164 retains dictionary-attested jabarr baldy gum tree; bare target only."),
    row(8, "The spiderlily is there.", "Jakari yinyay.", "jakari yinyay | spiderlily there", "r164_deictic_jakari_there", ["jakari", "yinyay"], "Rule 164 retains dictionary-attested jakari spiderlily; no medicine or use claim."),
    row(9, "The jama tree is there.", "Jama yinyay.", "jama yinyay | jama.tree there", "r164_deictic_jama_there", ["jama", "yinyay"], "Rule 164 retains dictionary-attested jama as a tree type; bare yinyay deictic frame."),
    row(10, "The corkwood tree is there.", "Jilbar yinyay.", "jilbar yinyay | corkwood.tree there", "r164_deictic_jilbar_there", ["jilbar", "yinyay"], "Rule 164 retains dictionary-attested jilbar corkwood tree; no wood/bark/material-use row."),
    row(11, "I see the buyukal tree here.", "Ngayu buyukal yaluy nyajil.", "ngayu buyukal yaluy nyaji-l | I buyukal.tree here see-NONPAST", "r164_present_i_buyukal_here", ["ngayu", "buyukal", "yaluy", "nyaji-l"], "Pronoun A bare; target tree object bare; yaluy is support only."),
    row(12, "I see the casuarina pine here.", "Ngayu dalkan yaluy nyajil.", "ngayu dalkan yaluy nyaji-l | I casuarina.pine here see-NONPAST", "r164_present_i_dalkan_here", ["ngayu", "dalkan", "yaluy", "nyaji-l"], "Pronoun A bare; dalkan object bare; no target locative."),
    row(13, "I see the boxwood tree here.", "Ngayu dari yaluy nyajil.", "ngayu dari yaluy nyaji-l | I boxwood.tree here see-NONPAST", "r164_present_i_dari_here", ["ngayu", "dari", "yaluy", "nyaji-l"], "Pronoun A bare; dari object bare; no ecology import."),
    row(14, "I see the cane here.", "Ngayu dibul yaluy nyajil.", "ngayu dibul yaluy nyaji-l | I cane here see-NONPAST", "r164_present_i_dibul_here", ["ngayu", "dibul", "yaluy", "nyaji-l"], "Pronoun A bare; dibul object bare; no cane-use claim."),
    row(15, "I see the hickory tree here.", "Ngayu dilbal yaluy nyajil.", "ngayu dilbal yaluy nyaji-l | I hickory.tree here see-NONPAST", "r164_present_i_dilbal_here", ["ngayu", "dilbal", "yaluy", "nyaji-l"], "Pronoun A bare; dilbal object bare."),
    row(16, "I see the corkwood pine here.", "Ngayu dili yaluy nyajil.", "ngayu dili yaluy nyaji-l | I corkwood.pine here see-NONPAST", "r164_present_i_dili_here", ["ngayu", "dili", "yaluy", "nyaji-l"], "Pronoun A bare; dili object bare, no dili-mba locative."),
    row(17, "I see the baldy gum tree here.", "Ngayu jabarr yaluy nyajil.", "ngayu jabarr yaluy nyaji-l | I baldy.gum.tree here see-NONPAST", "r164_present_i_jabarr_here", ["ngayu", "jabarr", "yaluy", "nyaji-l"], "Pronoun A bare; jabarr object bare."),
    row(18, "I see the spiderlily here.", "Ngayu jakari yaluy nyajil.", "ngayu jakari yaluy nyaji-l | I spiderlily here see-NONPAST", "r164_present_i_jakari_here", ["ngayu", "jakari", "yaluy", "nyaji-l"], "Pronoun A bare; jakari object bare; no medicine or use claim."),
    row(19, "I see the jama tree here.", "Ngayu jama yaluy nyajil.", "ngayu jama yaluy nyaji-l | I jama.tree here see-NONPAST", "r164_present_i_jama_here", ["ngayu", "jama", "yaluy", "nyaji-l"], "Pronoun A bare; jama object bare."),
    row(20, "I see the corkwood tree here.", "Ngayu jilbar yaluy nyajil.", "ngayu jilbar yaluy nyaji-l | I corkwood.tree here see-NONPAST", "r164_present_i_jilbar_here", ["ngayu", "jilbar", "yaluy", "nyaji-l"], "Pronoun A bare; jilbar object bare; no wood/bark/material row."),
    row(21, "You see the buyukal tree here.", "Yundu buyukal yaluy nyajil.", "yundu buyukal yaluy nyaji-l | you buyukal.tree here see-NONPAST", "r164_present_you_buyukal_here", ["yundu", "buyukal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; yaluy support only."),
    row(22, "You see the casuarina pine here.", "Yundu dalkan yaluy nyajil.", "yundu dalkan yaluy nyaji-l | you casuarina.pine here see-NONPAST", "r164_present_you_dalkan_here", ["yundu", "dalkan", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no target locative."),
    row(23, "You see the boxwood tree here.", "Yundu dari yaluy nyajil.", "yundu dari yaluy nyaji-l | you boxwood.tree here see-NONPAST", "r164_present_you_dari_here", ["yundu", "dari", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(24, "You see the cane here.", "Yundu dibul yaluy nyajil.", "yundu dibul yaluy nyaji-l | you cane here see-NONPAST", "r164_present_you_dibul_here", ["yundu", "dibul", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no tying/weaving/material claim."),
    row(25, "You see the hickory tree here.", "Yundu dilbal yaluy nyajil.", "yundu dilbal yaluy nyaji-l | you hickory.tree here see-NONPAST", "r164_present_you_dilbal_here", ["yundu", "dilbal", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(26, "You see the corkwood pine here.", "Yundu dili yaluy nyajil.", "yundu dili yaluy nyaji-l | you corkwood.pine here see-NONPAST", "r164_present_you_dili_here", ["yundu", "dili", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no dili-mba target form."),
    row(27, "You see the baldy gum tree here.", "Yundu jabarr yaluy nyajil.", "yundu jabarr yaluy nyaji-l | you baldy.gum.tree here see-NONPAST", "r164_present_you_jabarr_here", ["yundu", "jabarr", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(28, "You see the spiderlily here.", "Yundu jakari yaluy nyajil.", "yundu jakari yaluy nyaji-l | you spiderlily here see-NONPAST", "r164_present_you_jakari_here", ["yundu", "jakari", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no plant-use claim."),
    row(29, "You see the jama tree here.", "Yundu jama yaluy nyajil.", "yundu jama yaluy nyaji-l | you jama.tree here see-NONPAST", "r164_present_you_jama_here", ["yundu", "jama", "yaluy", "nyaji-l"], "Second-person pronoun A bare; target object bare."),
    row(30, "You see the corkwood tree here.", "Yundu jilbar yaluy nyajil.", "yundu jilbar yaluy nyaji-l | you corkwood.tree here see-NONPAST", "r164_present_you_jilbar_here", ["yundu", "jilbar", "yaluy", "nyaji-l"], "Second-person pronoun A bare; no wood/bark/material claim."),
    row(31, "They saw the buyukal tree here.", "Jana buyukal yaluy nyajin.", "jana buyukal yaluy nyaji-ny | they buyukal.tree here see-PAST", "r164_past_they_buyukal_here", ["jana", "buyukal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; past perception; target bare."),
    row(32, "They saw the casuarina pine here.", "Jana dalkan yaluy nyajin.", "jana dalkan yaluy nyaji-ny | they casuarina.pine here see-PAST", "r164_past_they_dalkan_here", ["jana", "dalkan", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no target locative."),
    row(33, "They saw the boxwood tree here.", "Jana dari yaluy nyajin.", "jana dari yaluy nyaji-ny | they boxwood.tree here see-PAST", "r164_past_they_dari_here", ["jana", "dari", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(34, "They saw the cane here.", "Jana dibul yaluy nyajin.", "jana dibul yaluy nyaji-ny | they cane here see-PAST", "r164_past_they_dibul_here", ["jana", "dibul", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no material-use row."),
    row(35, "They saw the hickory tree here.", "Jana dilbal yaluy nyajin.", "jana dilbal yaluy nyaji-ny | they hickory.tree here see-PAST", "r164_past_they_dilbal_here", ["jana", "dilbal", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(36, "They saw the corkwood pine here.", "Jana dili yaluy nyajin.", "jana dili yaluy nyaji-ny | they corkwood.pine here see-PAST", "r164_past_they_dili_here", ["jana", "dili", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no target locative."),
    row(37, "They saw the baldy gum tree here.", "Jana jabarr yaluy nyajin.", "jana jabarr yaluy nyaji-ny | they baldy.gum.tree here see-PAST", "r164_past_they_jabarr_here", ["jana", "jabarr", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(38, "They saw the spiderlily here.", "Jana jakari yaluy nyajin.", "jana jakari yaluy nyaji-ny | they spiderlily here see-PAST", "r164_past_they_jakari_here", ["jana", "jakari", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no plant-use claim."),
    row(39, "They saw the jama tree here.", "Jana jama yaluy nyajin.", "jana jama yaluy nyaji-ny | they jama.tree here see-PAST", "r164_past_they_jama_here", ["jana", "jama", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; target object bare."),
    row(40, "They saw the corkwood tree here.", "Jana jilbar yaluy nyajin.", "jana jilbar yaluy nyaji-ny | they corkwood.tree here see-PAST", "r164_past_they_jilbar_here", ["jana", "jilbar", "yaluy", "nyaji-l"], "Third-person plural pronoun A bare; no wood/bark/material claim."),
    row(41, "We see the buyukal tree there.", "Ngana buyukal yinyay nyajil.", "ngana buyukal yinyay nyaji-l | we buyukal.tree there see-NONPAST", "r164_present_we_buyukal_there", ["ngana", "buyukal", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; yinyay support only."),
    row(42, "We see the casuarina pine there.", "Ngana dalkan yinyay nyajil.", "ngana dalkan yinyay nyaji-l | we casuarina.pine there see-NONPAST", "r164_present_we_dalkan_there", ["ngana", "dalkan", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(43, "We see the boxwood tree there.", "Ngana dari yinyay nyajil.", "ngana dari yinyay nyaji-l | we boxwood.tree there see-NONPAST", "r164_present_we_dari_there", ["ngana", "dari", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(44, "We see the cane there.", "Ngana dibul yinyay nyajil.", "ngana dibul yinyay nyaji-l | we cane there see-NONPAST", "r164_present_we_dibul_there", ["ngana", "dibul", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no cane-use claim."),
    row(45, "We see the hickory tree there.", "Ngana dilbal yinyay nyajil.", "ngana dilbal yinyay nyaji-l | we hickory.tree there see-NONPAST", "r164_present_we_dilbal_there", ["ngana", "dilbal", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(46, "We see the corkwood pine there.", "Ngana dili yinyay nyajil.", "ngana dili yinyay nyaji-l | we corkwood.pine there see-NONPAST", "r164_present_we_dili_there", ["ngana", "dili", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no target locative."),
    row(47, "We see the baldy gum tree there.", "Ngana jabarr yinyay nyajil.", "ngana jabarr yinyay nyaji-l | we baldy.gum.tree there see-NONPAST", "r164_present_we_jabarr_there", ["ngana", "jabarr", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(48, "We see the spiderlily there.", "Ngana jakari yinyay nyajil.", "ngana jakari yinyay nyaji-l | we spiderlily there see-NONPAST", "r164_present_we_jakari_there", ["ngana", "jakari", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; no medicine or use claim."),
    row(49, "We see the jama tree there.", "Ngana jama yinyay nyajil.", "ngana jama yinyay nyaji-l | we jama.tree there see-NONPAST", "r164_present_we_jama_there", ["ngana", "jama", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare."),
    row(50, "We see the corkwood tree there.", "Ngana jilbar yinyay nyajil.", "ngana jilbar yinyay nyaji-l | we corkwood.tree there see-NONPAST", "r164_present_we_jilbar_there", ["ngana", "jilbar", "yinyay", "nyaji-l"], "Inclusive pronoun A bare; target object bare; no material-use claim."),
]


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("r164_"):
            issues.append(f"{label}: Rule 164 frame must start with r164_")
        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 164")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied plant-use/event 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 164 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 164 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 164 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 "saw" not in english_low):
                issues.append(f"{label}: rows 31-40 require jana + yaluy + 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 plant-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 164 draft: construction consolidation after Rule 163", "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 164 source pass retained the Rule 163 plant/tree set: buyukal, dalkan, dari, dibul, dilbal, dili, jabarr, jakari, jama, and jilbar. Dictionary exact readback confirmed all target heads. Patz readback confirmed dalkan-ba, bare dili/dili-mba, yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms; Rule 164 uses only bare target heads.",
                 command="rg dictionary exact readback; rg grammar readback for target/support/pronoun forms; sqlite lexeme 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 164 is a construction consolidation pass after Rule 163. It rotates the same ten plant/tree targets through bare yinyay deictic identification, yaluy-supported present perception with ngayu/yundu, yaluy-supported past perception with jana, and yinyay-supported present perception with ngana. It adds no new lexical heads and no use/event semantics.",
                 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_206.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 retained plant/tree target per row; all targets bare; no loans; no plant-use/event tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_206.py static scan", artifact_path="batch_scripts/bank_206.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())
