#!/usr/bin/env python3
"""Bank batch-222: Rule 180 construction consolidation after Rule 179."""

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

TARGET_HEADS = {
    "badibu": "spotted eagle ray",
    "bilaji": "flat-tailed ray",
    "bunjulu": "giant herring",
    "jilngu": "tarpon",
    "karrulji": "black spotted dart",
    "kilkirr": "tiger shark",
    "midir": "knight fish",
    "ngarmu": "shovelnose ray",
    "yalnganji": "manta ray",
    "yubuji": "sawfish",
}
PRONOUN_A = {"ngayu", "yundu", "jana", "ngana"}
DENY_KUKU = {
    "baban", "balarri", "barrbal", "bayil", "bayilbayil", "bilmbin", "bububay", "dalkal",
    "dalku", "dalmbal", "danbal", "dandarrbina", "dawal", "dijarr", "dukul-barangkal",
    "jalil-jalil", "jalkay", "janbal", "jarbir", "jijirr", "jindi", "judi", "jukar-jukarbina",
    "julaji", "julba", "julmba", "kalngkan", "kalu", "kanyaji", "kijukum", "kubarr",
    "kubija", "kubu-kubu", "kudi", "kundur-kundur", "kundurr-kundurr", "kurriyala", "kurruba",
    "kurrubal", "kuyu", "mangkurr-mangkurr", "mawul", "milkaji", "mujarrka", "murrabal",
    "murraja", "ngalkun", "ngiwa", "walarrji", "walbul-walbul", "walkan", "wara",
    "wuyumbu", "yaba", "yaburr", "yawu", "yidi", "yidilnyul",
    "badur", "makarr", "yinba", "yirrmba", "kanya", "banda",
}
DENY_ENGLISH = (
    "catch", "catches", "caught", "catching", "net", "hook", "line", "spear", "spears", "speared",
    "spearing", "eat", "eats", "ate", "eaten", "edible", "food", "meat", "cook", "cooked", "cooking",
    "taboo", "old people", "allowed to eat", "storm", "thunder", "rainstorm", "story", "story-site",
    "myth", "mythological", "place", "place-name", "river", "sea", "ocean", "water", "freshwater",
    "saltwater", "mangrove", "habitat", "reef", "scale", "fin", "tail", "body-part", "whiskers",
    "with whiskers", "source", "material", "use", "uses", "made", "poison", "danger", "bite", "bit",
    "biting", "kill", "killed", "hunting", "hunt", "plural", "many",
)


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 spotted eagle ray is there.", "Badibu yinyay.", "badibu yinyay | spotted.eagle.ray there", "r180_deictic_badibu_there", ["badibu", "yinyay"], "Rule 180 retains badibu as spotted eagle ray and rotates to yinyay deictic support."),
    row(2, "The flat-tailed ray is there.", "Bilaji yinyay.", "bilaji yinyay | flat-tailed.ray there", "r180_deictic_bilaji_there", ["bilaji", "yinyay"], "Rule 180 retains bilaji as flat-tailed ray; body-part analysis remains closed."),
    row(3, "The giant herring is there.", "Bunjulu yinyay.", "bunjulu yinyay | giant.herring there", "r180_deictic_bunjulu_there", ["bunjulu", "yinyay"], "Rule 180 retains bunjulu as giant herring; empty duplicate entry remains closed."),
    row(4, "The tarpon is there.", "Jilngu yinyay.", "jilngu yinyay | tarpon there", "r180_deictic_jilngu_there", ["jilngu", "yinyay"], "Rule 180 retains jilngu as tarpon; boney-salmon alternate prose remains closed."),
    row(5, "The black spotted dart is there.", "Karrulji yinyay.", "karrulji yinyay | black.spotted.dart there", "r180_deictic_karrulji_there", ["karrulji", "yinyay"], "Rule 180 retains karrulji as black spotted dart; no colour or action row."),
    row(6, "The tiger shark is there.", "Kilkirr yinyay.", "kilkirr yinyay | tiger.shark there", "r180_deictic_kilkirr_there", ["kilkirr", "yinyay"], "Rule 180 retains kilkirr as tiger shark; no danger or event row."),
    row(7, "The knight fish is there.", "Midir yinyay.", "midir yinyay | knight.fish there", "r180_deictic_midir_there", ["midir", "yinyay"], "Rule 180 retains midir as knight fish; port-and-light prose remains closed."),
    row(8, "The shovelnose ray is there.", "Ngarmu yinyay.", "ngarmu yinyay | shovelnose.ray there", "r180_deictic_ngarmu_there", ["ngarmu", "yinyay"], "Rule 180 retains ngarmu as shovelnose ray; no nose/body-part row."),
    row(9, "The manta ray is there.", "Yalnganji yinyay.", "yalnganji yinyay | manta.ray there", "r180_deictic_yalnganji_there", ["yalnganji", "yinyay"], "Rule 180 retains yalnganji as Yalanji manta ray; Nyungkul yidi stays closed."),
    row(10, "The sawfish is there.", "Yubuji yinyay.", "yubuji yinyay | sawfish there", "r180_deictic_yubuji_there", ["yubuji", "yinyay"], "Rule 180 retains yubuji as sawfish; no saw/cutting/action row."),
    row(11, "I see the spotted eagle ray here.", "Ngayu badibu yaluy nyajil.", "ngayu badibu yaluy nyaji-l | I spotted.eagle.ray here see-NONPAST", "r180_present_i_badibu_here", ["ngayu", "badibu", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; target object bare."),
    row(12, "I see the flat-tailed ray here.", "Ngayu bilaji yaluy nyajil.", "ngayu bilaji yaluy nyaji-l | I flat-tailed.ray here see-NONPAST", "r180_present_i_bilaji_here", ["ngayu", "bilaji", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; target object bare."),
    row(13, "I see the giant herring here.", "Ngayu bunjulu yaluy nyajil.", "ngayu bunjulu yaluy nyaji-l | I giant.herring here see-NONPAST", "r180_present_i_bunjulu_here", ["ngayu", "bunjulu", "yaluy", "nyaji-l"], "First-person present perception; empty duplicate entry not used."),
    row(14, "I see the tarpon here.", "Ngayu jilngu yaluy nyajil.", "ngayu jilngu yaluy nyaji-l | I tarpon here see-NONPAST", "r180_present_i_jilngu_here", ["ngayu", "jilngu", "yaluy", "nyaji-l"], "First-person present perception; selected tarpon sense only."),
    row(15, "I see the black spotted dart here.", "Ngayu karrulji yaluy nyajil.", "ngayu karrulji yaluy nyaji-l | I black.spotted.dart here see-NONPAST", "r180_present_i_karrulji_here", ["ngayu", "karrulji", "yaluy", "nyaji-l"], "First-person present perception with yaluy support; no colour predicate."),
    row(16, "I see the tiger shark here.", "Ngayu kilkirr yaluy nyajil.", "ngayu kilkirr yaluy nyaji-l | I tiger.shark here see-NONPAST", "r180_present_i_kilkirr_here", ["ngayu", "kilkirr", "yaluy", "nyaji-l"], "First-person present perception; no danger, bite, or hunting claim."),
    row(17, "I see the knight fish here.", "Ngayu midir yaluy nyajil.", "ngayu midir yaluy nyaji-l | I knight.fish here see-NONPAST", "r180_present_i_midir_here", ["ngayu", "midir", "yaluy", "nyaji-l"], "First-person present perception; port-and-light prose not imported."),
    row(18, "I see the shovelnose ray here.", "Ngayu ngarmu yaluy nyajil.", "ngayu ngarmu yaluy nyaji-l | I shovelnose.ray here see-NONPAST", "r180_present_i_ngarmu_here", ["ngayu", "ngarmu", "yaluy", "nyaji-l"], "First-person present perception; target object bare."),
    row(19, "I see the manta ray here.", "Ngayu yalnganji yaluy nyajil.", "ngayu yalnganji yaluy nyaji-l | I manta.ray here see-NONPAST", "r180_present_i_yalnganji_here", ["ngayu", "yalnganji", "yaluy", "nyaji-l"], "First-person present perception; Yalanji target selected."),
    row(20, "I see the sawfish here.", "Ngayu yubuji yaluy nyajil.", "ngayu yubuji yaluy nyaji-l | I sawfish here see-NONPAST", "r180_present_i_yubuji_here", ["ngayu", "yubuji", "yaluy", "nyaji-l"], "First-person present perception; no saw/cutting/action row."),
    row(21, "You see the spotted eagle ray here.", "Yundu badibu yaluy nyajil.", "yundu badibu yaluy nyaji-l | you spotted.eagle.ray here see-NONPAST", "r180_present_you_badibu_here", ["yundu", "badibu", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(22, "You see the flat-tailed ray here.", "Yundu bilaji yaluy nyajil.", "yundu bilaji yaluy nyaji-l | you flat-tailed.ray here see-NONPAST", "r180_present_you_bilaji_here", ["yundu", "bilaji", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(23, "You see the giant herring here.", "Yundu bunjulu yaluy nyajil.", "yundu bunjulu yaluy nyaji-l | you giant.herring here see-NONPAST", "r180_present_you_bunjulu_here", ["yundu", "bunjulu", "yaluy", "nyaji-l"], "Second-person present perception; empty duplicate entry not used."),
    row(24, "You see the tarpon here.", "Yundu jilngu yaluy nyajil.", "yundu jilngu yaluy nyaji-l | you tarpon here see-NONPAST", "r180_present_you_jilngu_here", ["yundu", "jilngu", "yaluy", "nyaji-l"], "Second-person present perception; selected tarpon sense only."),
    row(25, "You see the black spotted dart here.", "Yundu karrulji yaluy nyajil.", "yundu karrulji yaluy nyaji-l | you black.spotted.dart here see-NONPAST", "r180_present_you_karrulji_here", ["yundu", "karrulji", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(26, "You see the tiger shark here.", "Yundu kilkirr yaluy nyajil.", "yundu kilkirr yaluy nyaji-l | you tiger.shark here see-NONPAST", "r180_present_you_kilkirr_here", ["yundu", "kilkirr", "yaluy", "nyaji-l"], "Second-person present perception; no danger/event row."),
    row(27, "You see the knight fish here.", "Yundu midir yaluy nyajil.", "yundu midir yaluy nyaji-l | you knight.fish here see-NONPAST", "r180_present_you_midir_here", ["yundu", "midir", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(28, "You see the shovelnose ray here.", "Yundu ngarmu yaluy nyajil.", "yundu ngarmu yaluy nyaji-l | you shovelnose.ray here see-NONPAST", "r180_present_you_ngarmu_here", ["yundu", "ngarmu", "yaluy", "nyaji-l"], "Second-person present perception with yaluy support."),
    row(29, "You see the manta ray here.", "Yundu yalnganji yaluy nyajil.", "yundu yalnganji yaluy nyaji-l | you manta.ray here see-NONPAST", "r180_present_you_yalnganji_here", ["yundu", "yalnganji", "yaluy", "nyaji-l"], "Second-person present perception; Yalanji target selected."),
    row(30, "You see the sawfish here.", "Yundu yubuji yaluy nyajil.", "yundu yubuji yaluy nyaji-l | you sawfish here see-NONPAST", "r180_present_you_yubuji_here", ["yundu", "yubuji", "yaluy", "nyaji-l"], "Second-person present perception; target object bare."),
    row(31, "They saw the spotted eagle ray here.", "Jana badibu yaluy nyajin.", "jana badibu yaluy nyaji-ny | they spotted.eagle.ray here see-PAST", "r180_past_they_badibu_here", ["jana", "badibu", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(32, "They saw the flat-tailed ray here.", "Jana bilaji yaluy nyajin.", "jana bilaji yaluy nyaji-ny | they flat-tailed.ray here see-PAST", "r180_past_they_bilaji_here", ["jana", "bilaji", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(33, "They saw the giant herring here.", "Jana bunjulu yaluy nyajin.", "jana bunjulu yaluy nyaji-ny | they giant.herring here see-PAST", "r180_past_they_bunjulu_here", ["jana", "bunjulu", "yaluy", "nyaji-l"], "Third-person plural past perception; empty duplicate entry not used."),
    row(34, "They saw the tarpon here.", "Jana jilngu yaluy nyajin.", "jana jilngu yaluy nyaji-ny | they tarpon here see-PAST", "r180_past_they_jilngu_here", ["jana", "jilngu", "yaluy", "nyaji-l"], "Third-person plural past perception; selected tarpon sense only."),
    row(35, "They saw the black spotted dart here.", "Jana karrulji yaluy nyajin.", "jana karrulji yaluy nyaji-ny | they black.spotted.dart here see-PAST", "r180_past_they_karrulji_here", ["jana", "karrulji", "yaluy", "nyaji-l"], "Third-person plural past perception with yaluy support."),
    row(36, "They saw the tiger shark here.", "Jana kilkirr yaluy nyajin.", "jana kilkirr yaluy nyaji-ny | they tiger.shark here see-PAST", "r180_past_they_kilkirr_here", ["jana", "kilkirr", "yaluy", "nyaji-l"], "Third-person plural past perception; no danger/event row."),
    row(37, "They saw the knight fish here.", "Jana midir yaluy nyajin.", "jana midir yaluy nyaji-ny | they knight.fish here see-PAST", "r180_past_they_midir_here", ["jana", "midir", "yaluy", "nyaji-l"], "Third-person plural past perception; port-and-light prose closed."),
    row(38, "They saw the shovelnose ray here.", "Jana ngarmu yaluy nyajin.", "jana ngarmu yaluy nyaji-ny | they shovelnose.ray here see-PAST", "r180_past_they_ngarmu_here", ["jana", "ngarmu", "yaluy", "nyaji-l"], "Third-person plural past perception; target object bare."),
    row(39, "They saw the manta ray here.", "Jana yalnganji yaluy nyajin.", "jana yalnganji yaluy nyaji-ny | they manta.ray here see-PAST", "r180_past_they_yalnganji_here", ["jana", "yalnganji", "yaluy", "nyaji-l"], "Third-person plural past perception; Yalanji target selected."),
    row(40, "They saw the sawfish here.", "Jana yubuji yaluy nyajin.", "jana yubuji yaluy nyaji-ny | they sawfish here see-PAST", "r180_past_they_yubuji_here", ["jana", "yubuji", "yaluy", "nyaji-l"], "Third-person plural past perception; no saw/cutting/action row."),
    row(41, "We see the spotted eagle ray there.", "Ngana badibu yinyay nyajil.", "ngana badibu yinyay nyaji-l | we spotted.eagle.ray there see-NONPAST", "r180_present_we_badibu_there", ["ngana", "badibu", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(42, "We see the flat-tailed ray there.", "Ngana bilaji yinyay nyajil.", "ngana bilaji yinyay nyaji-l | we flat-tailed.ray there see-NONPAST", "r180_present_we_bilaji_there", ["ngana", "bilaji", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(43, "We see the giant herring there.", "Ngana bunjulu yinyay nyajil.", "ngana bunjulu yinyay nyaji-l | we giant.herring there see-NONPAST", "r180_present_we_bunjulu_there", ["ngana", "bunjulu", "yinyay", "nyaji-l"], "Inclusive present perception; empty duplicate entry not used."),
    row(44, "We see the tarpon there.", "Ngana jilngu yinyay nyajil.", "ngana jilngu yinyay nyaji-l | we tarpon there see-NONPAST", "r180_present_we_jilngu_there", ["ngana", "jilngu", "yinyay", "nyaji-l"], "Inclusive present perception; selected tarpon sense only."),
    row(45, "We see the black spotted dart there.", "Ngana karrulji yinyay nyajil.", "ngana karrulji yinyay nyaji-l | we black.spotted.dart there see-NONPAST", "r180_present_we_karrulji_there", ["ngana", "karrulji", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(46, "We see the tiger shark there.", "Ngana kilkirr yinyay nyajil.", "ngana kilkirr yinyay nyaji-l | we tiger.shark there see-NONPAST", "r180_present_we_kilkirr_there", ["ngana", "kilkirr", "yinyay", "nyaji-l"], "Inclusive present perception; no danger/event row."),
    row(47, "We see the knight fish there.", "Ngana midir yinyay nyajil.", "ngana midir yinyay nyaji-l | we knight.fish there see-NONPAST", "r180_present_we_midir_there", ["ngana", "midir", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(48, "We see the shovelnose ray there.", "Ngana ngarmu yinyay nyajil.", "ngana ngarmu yinyay nyaji-l | we shovelnose.ray there see-NONPAST", "r180_present_we_ngarmu_there", ["ngana", "ngarmu", "yinyay", "nyaji-l"], "Inclusive present perception with yinyay support."),
    row(49, "We see the manta ray there.", "Ngana yalnganji yinyay nyajil.", "ngana yalnganji yinyay nyaji-l | we manta.ray there see-NONPAST", "r180_present_we_yalnganji_there", ["ngana", "yalnganji", "yinyay", "nyaji-l"], "Inclusive present perception; Yalanji target selected."),
    row(50, "We see the sawfish there.", "Ngana yubuji yinyay nyajil.", "ngana yubuji yinyay nyaji-l | we sawfish there see-NONPAST", "r180_present_we_yubuji_there", ["ngana", "yubuji", "yinyay", "nyaji-l"], "Inclusive present perception; no saw/cutting/action 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 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("r180_"):
            issues.append(f"{label}: Rule 180 frame must start with r180_")
        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 180")
        for denied in DENY_KUKU:
            if has_token(low, denied):
                issues.append(f"{label}: denied fish/use/old-field 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 retained Rule 179 target head, found {targets}")
        for head in targets:
            selected = TARGET_HEADS[head]
            if head not in words:
                issues.append(f"{label}: target head {head} missing from words_used")
            if selected.replace(" ", ".") not in analysis:
                issues.append(f"{label}: target head {head} must be glossed as {selected}")
            if selected not in english_low:
                issues.append(f"{label}: {head} must be translated with selected sense {selected!r}")
            if has_target_case(low, head):
                issues.append(f"{label}: target head {head} has forbidden case/compound morphology")
        if seq <= 10:
            if "nyajil" in low or "nyajin" in low or "nyaji-l" in words:
                issues.append(f"{label}: deictic rows must not use nyaji-l")
            if not has_token(low, "yinyay") or "yinyay" not in words or "there" not in english_low:
                issues.append(f"{label}: Rule 180 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 180 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 fish 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 180 draft: construction consolidation after Rule 179", "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 180 source pass retained exactly the ten Rule 179 fish/ray reference heads: badibu, bilaji, bunjulu, jilngu, karrulji, kilkirr, midir, ngarmu, yalnganji, and yubuji. Fresh YAML readback reconfirmed selected senses and known traps: duplicate fish entries, empty duplicate bunjulu, jilngu alternate prose, midir port-and-light prose, and Nyungkul yidi under yalnganji. Patz readback reconfirmed yaluy/yinyay, nyaji-l/nyaji-ny, and bare pronoun A forms. Corpus readback found the heads present through Batch 221 and zero Batch 222 rows before banking.",
                 command="structured dictionary YAML readback; rg grammar readback; sqlite 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 180 is a construction consolidation pass for the Rule 179 fish/ray field. It admits no new fish heads and excludes catching, netting, hook/line, spearing, eating, cooking, food, taboo, storm/thunder, story, place, water/river/sea/habitat, fish body-part terms, target case, target compounds, possession, plural derivation, 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_222.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 Rule 179 fish/ray target per row; all targets bare; no loans; no old fish/use/event/polysemy tokens; no target case/compound forms; pronoun A bare; yinyay/yaluy support only.",
                 command="python3 batch_scripts/bank_222.py static scan", artifact_path="batch_scripts/bank_222.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())
