#!/usr/bin/env python3
"""Bank batch-246: Rule 204 negated surface-property consolidation."""

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

TARGET_HEADS = {
    "mulun": "folded",
    "dangal": "baggy",
    "dulngki": "wide",
    "dungkul": "huge",
    "dunju-dunju": "coarse",
    "jala-jala": "loose",
    "jalkar-jalkar": "steep",
    "yuku": "thick",
    "muja-muja": "rotten",
    "nguyal": "sticky",
}
SUBJECT_HEADS = {"kambi", "baral", "bayan", "juku", "mayi"}
SUPPORT = {"kari", "yinya", "yaluy", "yinyay"} | SUBJECT_HEADS
DENY_KUKU = {
    "nyaji-l", "nyajil", "nyajin", "baral-l", "baral-y", "bajaku", "baja",
    "nuka", "nukal", "nukan", "waju", "wajul", "wajun", "mani", "manil", "manin",
    "dunga", "dungan", "dungay", "warri", "warriny", "daka", "dakany", "dakay",
    "kida", "kidal", "kidan", "yaka", "yakan", "yakay", "kuni", "kunil", "kunin",
    "ngara", "ngaran", "bunday", "bundanda", "ngaki", "ngakiny", "ngakiji",
    "yala", "yanyu",
    "kawal", "ngawungkal", "ngulnkul", "nyinja", "wungka", "kandarr", "ngangkun", "wankun",
    "warimaji", "kunji", "jangkuy", "kankar", "nginja", "numburr", "yanja", "kadil", "kuwimbur",
    "ngangkurr", "ngingkirr",
    "jinjajalka", "kurunkal", "madu", "marngkil", "marrabal", "milbarakal", "mungari",
    "wurmbariji", "wuymbariji", "kurrun",
}
DENY_ENGLISH = (
    "hear", "heard", "hearing", "listen", "listening", "perceive", "perceived", "see", "saw", "feel", "felt",
    "eat", "eating", "cook", "cooking", "cooked", "gather", "gathering", "cut", "cutting", "chop", "chopping",
    "make", "making", "wear", "wearing", "sew", "sewing", "repair", "patched", "travel", "walk", "go", "going",
    "folding", "opening", "closing", "road along", "country", "owner", "ownership", "ill", "illness", "sick",
    "sickness", "body", "pain", "sound", "tree-use", "source", "because", "very", "more",
)


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


ROWS = [
    row(1, "The clothing is not folded.", "Kambi kari mulun.", "kambi kari mulun | clothing NEG folded", "r204_np_kari_adj_kambi_mulun", ["kambi", "kari", "mulun"], "Patz negative particle before predicator; Rule 203 mulun."),
    row(2, "The clothing is not baggy.", "Kambi kari dangal.", "kambi kari dangal | clothing NEG baggy", "r204_np_kari_adj_kambi_dangal", ["kambi", "kari", "dangal"], "Independent kari negates property predicate; no clothing event."),
    row(3, "The road is not wide.", "Baral kari dulngki.", "baral kari dulngki | road NEG wide", "r204_np_kari_adj_baral_dulngki", ["baral", "kari", "dulngki"], "Baral road/path noun only; no feel/perception verb."),
    row(4, "The house is not huge.", "Bayan kari dungkul.", "bayan kari dungkul | house NEG huge", "r204_np_kari_adj_bayan_dungkul", ["bayan", "kari", "dungkul"], "Bayan house/camp support; no ownership/repair row."),
    row(5, "The wood is not coarse.", "Juku kari dunju-dunju.", "juku kari dunju-dunju | wood NEG coarse", "r204_np_kari_adj_juku_dunju_dunju", ["juku", "kari", "dunju-dunju"], "Lexicalized adjective; no productive reduplication."),
    row(6, "The clothing is not loose.", "Kambi kari jala-jala.", "kambi kari jala-jala | clothing NEG loose", "r204_np_kari_adj_kambi_jala_jala", ["kambi", "kari", "jala-jala"], "Lexicalized adjective; no wearing/making row."),
    row(7, "The road is not steep.", "Baral kari jalkar-jalkar.", "baral kari jalkar-jalkar | road NEG steep", "r204_np_kari_adj_baral_jalkar_jalkar", ["baral", "kari", "jalkar-jalkar"], "Lexicalized adjective; no travel event."),
    row(8, "The wood is not thick.", "Juku kari yuku.", "juku kari yuku | wood NEG thick", "r204_np_kari_adj_juku_yuku", ["juku", "kari", "yuku"], "Yuku selected as thick only; no wood-use row."),
    row(9, "The wood is not rotten.", "Juku kari muja-muja.", "juku kari muja-muja | wood NEG rotten", "r204_np_kari_adj_juku_muja_muja", ["juku", "kari", "muja-muja"], "Rotten/decayed property only; no cutting/use row."),
    row(10, "The food is not sticky.", "Mayi kari nguyal.", "mayi kari nguyal | food NEG sticky", "r204_np_kari_adj_mayi_nguyal", ["mayi", "kari", "nguyal"], "Food noun only; no eating/cooking row."),
    row(11, "That clothing is not folded.", "Yinya kambi kari mulun.", "yinya kambi kari mulun | that clothing NEG folded", "r204_yinya_np_kari_adj_kambi_mulun", ["yinya", "kambi", "kari", "mulun"], "Patz example 295 yinya NP ADJ plus independent kari."),
    row(12, "That clothing is not baggy.", "Yinya kambi kari dangal.", "yinya kambi kari dangal | that clothing NEG baggy", "r204_yinya_np_kari_adj_kambi_dangal", ["yinya", "kambi", "kari", "dangal"], "Initial yinya support; no clothing event."),
    row(13, "That road is not wide.", "Yinya baral kari dulngki.", "yinya baral kari dulngki | that road NEG wide", "r204_yinya_np_kari_adj_baral_dulngki", ["yinya", "baral", "kari", "dulngki"], "Initial yinya support; baral road/path noun only."),
    row(14, "That house is not huge.", "Yinya bayan kari dungkul.", "yinya bayan kari dungkul | that house NEG huge", "r204_yinya_np_kari_adj_bayan_dungkul", ["yinya", "bayan", "kari", "dungkul"], "Initial yinya support; no repair/ownership row."),
    row(15, "That wood is not coarse.", "Yinya juku kari dunju-dunju.", "yinya juku kari dunju-dunju | that wood NEG coarse", "r204_yinya_np_kari_adj_juku_dunju_dunju", ["yinya", "juku", "kari", "dunju-dunju"], "Initial yinya support; no target morphology."),
    row(16, "That clothing is not loose.", "Yinya kambi kari jala-jala.", "yinya kambi kari jala-jala | that clothing NEG loose", "r204_yinya_np_kari_adj_kambi_jala_jala", ["yinya", "kambi", "kari", "jala-jala"], "Initial yinya support; no productive reduplication."),
    row(17, "That road is not steep.", "Yinya baral kari jalkar-jalkar.", "yinya baral kari jalkar-jalkar | that road NEG steep", "r204_yinya_np_kari_adj_baral_jalkar_jalkar", ["yinya", "baral", "kari", "jalkar-jalkar"], "Initial yinya support; no route/travel row."),
    row(18, "That wood is not thick.", "Yinya juku kari yuku.", "yinya juku kari yuku | that wood NEG thick", "r204_yinya_np_kari_adj_juku_yuku", ["yinya", "juku", "kari", "yuku"], "Initial yinya support; yuku thick only."),
    row(19, "That wood is not rotten.", "Yinya juku kari muja-muja.", "yinya juku kari muja-muja | that wood NEG rotten", "r204_yinya_np_kari_adj_juku_muja_muja", ["yinya", "juku", "kari", "muja-muja"], "Initial yinya support; no cutting/use row."),
    row(20, "That food is not sticky.", "Yinya mayi kari nguyal.", "yinya mayi kari nguyal | that food NEG sticky", "r204_yinya_np_kari_adj_mayi_nguyal", ["yinya", "mayi", "kari", "nguyal"], "Initial yinya support; no eating/cooking row."),
    row(21, "The clothing here is not folded.", "Kambi kari mulun yaluy.", "kambi kari mulun yaluy | clothing NEG folded here", "r204_np_kari_adj_here_kambi_mulun", ["kambi", "kari", "mulun", "yaluy"], "Rule 238/245 deictic property support plus independent kari."),
    row(22, "The clothing here is not baggy.", "Kambi kari dangal yaluy.", "kambi kari dangal yaluy | clothing NEG baggy here", "r204_np_kari_adj_here_kambi_dangal", ["kambi", "kari", "dangal", "yaluy"], "Local support only; no clothing event."),
    row(23, "The road here is not wide.", "Baral kari dulngki yaluy.", "baral kari dulngki yaluy | road NEG wide here", "r204_np_kari_adj_here_baral_dulngki", ["baral", "kari", "dulngki", "yaluy"], "Local support only; no travel event."),
    row(24, "The house here is not huge.", "Bayan kari dungkul yaluy.", "bayan kari dungkul yaluy | house NEG huge here", "r204_np_kari_adj_here_bayan_dungkul", ["bayan", "kari", "dungkul", "yaluy"], "Local support only; no repair row."),
    row(25, "The wood here is not coarse.", "Juku kari dunju-dunju yaluy.", "juku kari dunju-dunju yaluy | wood NEG coarse here", "r204_np_kari_adj_here_juku_dunju_dunju", ["juku", "kari", "dunju-dunju", "yaluy"], "Local support only; no cutting/use row."),
    row(26, "The clothing here is not loose.", "Kambi kari jala-jala yaluy.", "kambi kari jala-jala yaluy | clothing NEG loose here", "r204_np_kari_adj_here_kambi_jala_jala", ["kambi", "kari", "jala-jala", "yaluy"], "Local support only; no wearing/making row."),
    row(27, "The road here is not steep.", "Baral kari jalkar-jalkar yaluy.", "baral kari jalkar-jalkar yaluy | road NEG steep here", "r204_np_kari_adj_here_baral_jalkar_jalkar", ["baral", "kari", "jalkar-jalkar", "yaluy"], "Local support only; no route/travel row."),
    row(28, "The wood here is not thick.", "Juku kari yuku yaluy.", "juku kari yuku yaluy | wood NEG thick here", "r204_np_kari_adj_here_juku_yuku", ["juku", "kari", "yuku", "yaluy"], "Local support only; no wood-use row."),
    row(29, "The wood here is not rotten.", "Juku kari muja-muja yaluy.", "juku kari muja-muja yaluy | wood NEG rotten here", "r204_np_kari_adj_here_juku_muja_muja", ["juku", "kari", "muja-muja", "yaluy"], "Local support only; no cutting/use row."),
    row(30, "The food here is not sticky.", "Mayi kari nguyal yaluy.", "mayi kari nguyal yaluy | food NEG sticky here", "r204_np_kari_adj_here_mayi_nguyal", ["mayi", "kari", "nguyal", "yaluy"], "Local support only; no eating/cooking row."),
    row(31, "The clothing there is not folded.", "Kambi kari mulun yinyay.", "kambi kari mulun yinyay | clothing NEG folded there", "r204_np_kari_adj_there_kambi_mulun", ["kambi", "kari", "mulun", "yinyay"], "Yinyay support only; no clothing event."),
    row(32, "The clothing there is not baggy.", "Kambi kari dangal yinyay.", "kambi kari dangal yinyay | clothing NEG baggy there", "r204_np_kari_adj_there_kambi_dangal", ["kambi", "kari", "dangal", "yinyay"], "Yinyay support only; no wearing/making row."),
    row(33, "The road there is not wide.", "Baral kari dulngki yinyay.", "baral kari dulngki yinyay | road NEG wide there", "r204_np_kari_adj_there_baral_dulngki", ["baral", "kari", "dulngki", "yinyay"], "Yinyay support only; no travel event."),
    row(34, "The house there is not huge.", "Bayan kari dungkul yinyay.", "bayan kari dungkul yinyay | house NEG huge there", "r204_np_kari_adj_there_bayan_dungkul", ["bayan", "kari", "dungkul", "yinyay"], "Yinyay support only; no ownership/repair row."),
    row(35, "The wood there is not coarse.", "Juku kari dunju-dunju yinyay.", "juku kari dunju-dunju yinyay | wood NEG coarse there", "r204_np_kari_adj_there_juku_dunju_dunju", ["juku", "kari", "dunju-dunju", "yinyay"], "Yinyay support only; no tree-use/source row."),
    row(36, "The clothing there is not loose.", "Kambi kari jala-jala yinyay.", "kambi kari jala-jala yinyay | clothing NEG loose there", "r204_np_kari_adj_there_kambi_jala_jala", ["kambi", "kari", "jala-jala", "yinyay"], "Yinyay support only; no clothing event."),
    row(37, "The road there is not steep.", "Baral kari jalkar-jalkar yinyay.", "baral kari jalkar-jalkar yinyay | road NEG steep there", "r204_np_kari_adj_there_baral_jalkar_jalkar", ["baral", "kari", "jalkar-jalkar", "yinyay"], "Yinyay support only; no route/travel row."),
    row(38, "The wood there is not thick.", "Juku kari yuku yinyay.", "juku kari yuku yinyay | wood NEG thick there", "r204_np_kari_adj_there_juku_yuku", ["juku", "kari", "yuku", "yinyay"], "Yinyay support only; no wood-use row."),
    row(39, "The wood there is not rotten.", "Juku kari muja-muja yinyay.", "juku kari muja-muja yinyay | wood NEG rotten there", "r204_np_kari_adj_there_juku_muja_muja", ["juku", "kari", "muja-muja", "yinyay"], "Yinyay support only; no cutting/use row."),
    row(40, "The food there is not sticky.", "Mayi kari nguyal yinyay.", "mayi kari nguyal yinyay | food NEG sticky there", "r204_np_kari_adj_there_mayi_nguyal", ["mayi", "kari", "nguyal", "yinyay"], "Yinyay support only; no eating/cooking row."),
    row(41, "That clothing there is not folded.", "Yinya kambi kari mulun yinyay.", "yinya kambi kari mulun yinyay | that clothing NEG folded there", "r204_yinya_np_kari_adj_there_kambi_mulun", ["yinya", "kambi", "kari", "mulun", "yinyay"], "Yinya plus yinyay support; no support inflection."),
    row(42, "That clothing there is not baggy.", "Yinya kambi kari dangal yinyay.", "yinya kambi kari dangal yinyay | that clothing NEG baggy there", "r204_yinya_np_kari_adj_there_kambi_dangal", ["yinya", "kambi", "kari", "dangal", "yinyay"], "Yinya plus yinyay support; no clothing event."),
    row(43, "That road there is not wide.", "Yinya baral kari dulngki yinyay.", "yinya baral kari dulngki yinyay | that road NEG wide there", "r204_yinya_np_kari_adj_there_baral_dulngki", ["yinya", "baral", "kari", "dulngki", "yinyay"], "Yinya plus yinyay support; baral noun only."),
    row(44, "That house there is not huge.", "Yinya bayan kari dungkul yinyay.", "yinya bayan kari dungkul yinyay | that house NEG huge there", "r204_yinya_np_kari_adj_there_bayan_dungkul", ["yinya", "bayan", "kari", "dungkul", "yinyay"], "Yinya plus yinyay support; no repair/ownership row."),
    row(45, "That wood there is not coarse.", "Yinya juku kari dunju-dunju yinyay.", "yinya juku kari dunju-dunju yinyay | that wood NEG coarse there", "r204_yinya_np_kari_adj_there_juku_dunju_dunju", ["yinya", "juku", "kari", "dunju-dunju", "yinyay"], "Yinya plus yinyay support; no target morphology."),
    row(46, "That clothing there is not loose.", "Yinya kambi kari jala-jala yinyay.", "yinya kambi kari jala-jala yinyay | that clothing NEG loose there", "r204_yinya_np_kari_adj_there_kambi_jala_jala", ["yinya", "kambi", "kari", "jala-jala", "yinyay"], "Yinya plus yinyay support; no productive reduplication."),
    row(47, "That road there is not steep.", "Yinya baral kari jalkar-jalkar yinyay.", "yinya baral kari jalkar-jalkar yinyay | that road NEG steep there", "r204_yinya_np_kari_adj_there_baral_jalkar_jalkar", ["yinya", "baral", "kari", "jalkar-jalkar", "yinyay"], "Yinya plus yinyay support; no route/travel row."),
    row(48, "That wood there is not thick.", "Yinya juku kari yuku yinyay.", "yinya juku kari yuku yinyay | that wood NEG thick there", "r204_yinya_np_kari_adj_there_juku_yuku", ["yinya", "juku", "kari", "yuku", "yinyay"], "Yinya plus yinyay support; no wood-use row."),
    row(49, "That wood there is not rotten.", "Yinya juku kari muja-muja yinyay.", "yinya juku kari muja-muja yinyay | that wood NEG rotten there", "r204_yinya_np_kari_adj_there_juku_muja_muja", ["yinya", "juku", "kari", "muja-muja", "yinyay"], "Yinya plus yinyay support; no cutting/use row."),
    row(50, "That food there is not sticky.", "Yinya mayi kari nguyal yinyay.", "yinya mayi kari nguyal yinyay | that food NEG sticky there", "r204_yinya_np_kari_adj_there_mayi_nguyal", ["yinya", "mayi", "kari", "nguyal", "yinyay"], "Yinya plus yinyay support; no eating/cooking row."),
]


def has_token(low: str, token: str) -> bool:
    return re.search(rf"(?<![a-z-]){re.escape(token)}(?![a-z-])", low) is not None


def has_target_morphology(low: str, head: str) -> bool:
    suffixes = "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|baja|bungal|bungan|mal|man|rriny"
    return re.search(rf"(?<![a-z-]){re.escape(head)}-(?:{suffixes})\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("r204_"):
            issues.append(f"{label}: Rule 204 frame must start with r204_")
        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 204")
        if "-kari" in low:
            issues.append(f"{label}: privative -kari is forbidden in Rule 204")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied carry-forward 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 204 target adjective, found {targets}")
        subjects = [head for head in SUBJECT_HEADS if has_token(low, head)]
        if len(subjects) != 1:
            issues.append(f"{label}: expected exactly one support subject noun, found {subjects}")
        if not has_token(low, "kari"):
            issues.append(f"{label}: every Rule 204 row requires independent kari")
        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 not in english_low:
                issues.append(f"{label}: English must include selected sense {selected!r}")
            if selected not in analysis:
                issues.append(f"{label}: analysis must gloss {head} as {selected}")
            if has_target_morphology(low, head):
                issues.append(f"{label}: target head {head} has forbidden morphology")
        for support in SUPPORT:
            if has_token(low, support) and support not in words:
                issues.append(f"{label}: support {support} missing from words_used")
        if 1 <= seq <= 10 and (has_token(low, "yinya") or has_token(low, "yaluy") or has_token(low, "yinyay")):
            issues.append(f"{label}: rows 1-10 require NP kari ADJ")
        if 11 <= seq <= 20 and (not low.startswith("yinya ") or has_token(low, "yaluy") or has_token(low, "yinyay")):
            issues.append(f"{label}: rows 11-20 require Yinya NP kari ADJ")
        if 21 <= seq <= 30 and (has_token(low, "yinya") or has_token(low, "yinyay") or not low.endswith(" yaluy.")):
            issues.append(f"{label}: rows 21-30 require NP kari ADJ yaluy")
        if 31 <= seq <= 40 and (has_token(low, "yinya") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 31-40 require NP kari ADJ yinyay")
        if 41 <= seq <= 50 and (not low.startswith("yinya ") or has_token(low, "yaluy") or not low.endswith(" yinyay.")):
            issues.append(f"{label}: rows 41-50 require Yinya NP kari ADJ yinyay")
        if any(english_has_denied(english_low, bad) for bad in DENY_ENGLISH):
            issues.append(f"{label}: denied action/event/source/body-state field in English")
        if "not " not in english_low:
            issues.append(f"{label}: English must express negation with 'not'")
        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 204 draft: negated surface-property construction consolidation after Rule 203",
                "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 204 source pass retained the ten Rule 203 surface-property adjectives and selected negated property-predicate frames. Patz supports adjectives as property nominals, NP ADJ predicates, yinya NP ADJ predicates, and independent kari before the predicator in negative statements; Batch 237 provides local corpus precedent for NP kari ADJ and Yinya NP kari ADJ.",
        command="grammar.md readback for adjective predicates, yinya property predicate, and kari negative particle; batch-237/238/245 corpus precedent readback; sqlite duplicate preflight",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="scope",
        event_type="construction-scope",
        actor="claude-main",
        detail="Rule 204 is construction consolidation only: independent kari negates retained Rule 203 property predicates. It excludes privative -kari, perception verbs, degree/comparison, inchoative/causative, target case/compound/plural, events/actions, use/source claims, illness/body-state readings, support-noun homograph drift, and demonstrative inflection.",
        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 over all 50 planned negated surface-property surfaces returned no accepted/revised/under_review collisions.",
        command="sqlite exact lower(trim(kuku)) duplicate scan before banking",
        artifact_path="batch_scripts/bank_246.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="preflight",
        event_type="static-guard-pass",
        actor="claude-main",
        detail="Static guard passed: exactly 50 unique surfaces; exactly one target adjective and one support subject noun per row; every row has independent kari; no -kari, loans, nyaji-l/perception/degree/proximal-demonstrative tokens, denied event/source/body-state English, or target morphology; and correct five-frame distribution.",
        command="python3 batch_scripts/bank_246.py pre-bank scan",
        artifact_path="batch_scripts/bank_246.py",
        created_at=NOW,
    )

    db.executemany(
        """
        INSERT INTO sentences(
          batch_id, seq, english, kuku, analysis, frame, tier, words_used,
          loans_used, evidence, status, confidence, author, created_at, updated_at
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        """,
        [
            (
                batch_id,
                seq,
                english,
                kuku,
                analysis,
                frame,
                tier,
                words_used,
                loans_used,
                evidence,
                "under_review",
                confidence,
                "claude",
                NOW,
                NOW,
            )
            for seq, english, kuku, analysis, frame, tier, words_used, loans_used, evidence, confidence in ROWS
        ],
    )
    db.commit()

    count = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=?", (batch_id,)).fetchone()[0]
    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={count}, under_review={under_review}, verified_before_close={verified}")
    return 0


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