#!/usr/bin/env python3
"""Close batch-276 after main-loop five-lens review."""

from __future__ import annotations

import datetime as dt
import json
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-276"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-276-third-body-part-reference-lexical-expansion-after-rule233-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "THIRD BODY-PART REFERENCE LEXICAL EXPANSION AFTER RULE 233 (Rule 234). 50 rows. "
    "TARGETS: bandin love handles, bari chin, bibar shin, birri fingernail, jiba liver, jandal leg, "
    "jibar stomach, kangkul cheek, kuwinyu posterior, and waba thigh. SUPPORT: uninflected yinya/yaluy/yinyay. "
    "FRAMES: TARGET yaluy, TARGET yinyay, Yinya TARGET yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. "
    "REVIEW: all target nouns stayed bare body-part reference labels. No Rule 217/226 exact target repeat, no earlier "
    "common body-part exact-target repeat, no ritual/witchcraft/initiation, body-fluid/medical/sickness, animal-only, "
    "dialect-only, homograph-heavy, possession, body-state, movement/use/event, target case, target compound, productive "
    "reduplication, support inflection, or Rule 233 landform drift was opened."
)

LESSONS = [
    ("source", "Patz section 3.1 explicitly includes external and internal body parts in the noun class; Rule 234 uses that nominal body-part source only.", "Rule 234: nominal body-part source."),
    ("source", "Patz section 3.7 sources yinya 'that/those', yaluy 'here', and yinyay 'there'; Rule 234 keeps all support heads bare and uninflected.", "Rule 234: deictic source."),
    ("process", "Exact duplicate preflight over all 50 planned Rule 234 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 234: duplicate preflight."),
    ("process", "Junkan was dropped before authoring because 'back of ankle' created avoidable English/gloss edge risk; waba thigh was cleaner and source-backed.", "Rule 234: candidate swap."),
    ("lexicon", "Bandin is admitted as love-handles reference only; waist/hip prose, possession, body-state, and number morphology remain closed.", "Rule 234: bandin."),
    ("lexicon", "Bari is admitted as chin reference only; jaw alternation, face-state, injury, eating, and possession rows remain closed.", "Rule 234: bari."),
    ("lexicon", "Bibar is admitted as shin reference only; ankle alternation, walking, pain, injury, and possession rows remain closed.", "Rule 234: bibar."),
    ("lexicon", "Birri is admitted as fingernail reference only; toenail alternation, cutting, scratching, and possession rows remain closed.", "Rule 234: birri."),
    ("lexicon", "Jiba is admitted as liver reference only; insides/guts, emotion, sadness/gladness, eating, butchery, and possession rows remain closed.", "Rule 234: jiba."),
    ("lexicon", "Jandal is admitted as leg reference only; movement, walking, injury, and possession rows remain closed.", "Rule 234: jandal."),
    ("lexicon", "Jibar is admitted as stomach reference only; locational jibarr hinterland, emotion, sickness, eating, and possession rows remain closed.", "Rule 234: jibar."),
    ("lexicon", "Kangkul is admitted as cheek reference only; kangku valley drift, face-state, injury, and contact rows remain closed.", "Rule 234: kangkul."),
    ("lexicon", "Kuwinyu is admitted as posterior reference only; rude-register expansion, body-state, sitting, and possession rows remain closed.", "Rule 234: kuwinyu."),
    ("lexicon", "Waba is admitted as thigh reference only; hip alternation, grammar-source overreach, movement, injury, and possession rows remain closed.", "Rule 234: waba."),
    ("morphology", "All Rule 234 target nouns stayed bare: no target LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or suffixing.", "Rule 234: bare targets."),
    ("morphology", "Bandin's English plural is lexical/contextual only; no Kuku number morphology was introduced.", "Rule 234: lexical plural."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads; no demonstrative case, possessive, comitative, local-derived, plural-human, proximal, or support-inflection form was opened.", "Rule 234: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 234: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 234: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 234: preposed that-there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 234: postposed that-there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 234: preposed that-here frame."),
    ("fidelity", "English stayed literal body-part reference prose: selected body-part label plus here/there/that only.", "Rule 234: literal English."),
    ("fidelity", "The batch did not convert dictionary definitions into possession, pain, illness, medicine, body-fluid, ritual, animal, movement, event, or homograph claims.", "Rule 234: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements; posterior was retained because the dictionary explicitly marks kuwinyu as not rude.", "Rule 234: register."),
    ("process", "Rule 217 and Rule 226 exact targets stayed closed; earlier common body-part exact deictic surfaces were not repeated.", "Rule 234: prior target closure."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, source-book update, render, and live docs are required before treating Rule 234 as complete.", "Rule 234: evidence standard."),
    ("handoff", "Next batch may continue from 13,897 if this closes; do not infer body-part possession, case, pain, illness, movement, ritual, animal-only, dialect-only, or homograph grammar from Rule 234.", "Rule 234: next cadence."),
]

LEXEMES = [
    ("bandin", "noun", None, "NA", "love handles", "batch-276: love-handles reference only; lexical/contextual plural, no number morphology."),
    ("bari", "noun", None, "NA", "chin", "batch-276: chin reference only; jaw alternation remains closed."),
    ("bibar", "noun", None, "NA", "shin", "batch-276: shin reference only; ankle alternation remains closed."),
    ("birri", "noun", None, "NA", "fingernail", "batch-276: fingernail reference only; toenail alternation remains closed."),
    ("jiba", "noun", None, "NA", "liver", "batch-276: liver reference only; insides/guts and emotion prose remain closed."),
    ("jandal", "noun", None, "NA", "leg", "batch-276: leg reference only; no movement or injury row."),
    ("jibar", "noun", None, "NA", "stomach", "batch-276: stomach reference only; locational jibarr and emotion/sickness rows remain closed."),
    ("kangkul", "noun", None, "NA", "cheek", "batch-276: cheek reference only; kangku valley drift closed."),
    ("kuwinyu", "noun", None, "NA", "posterior", "batch-276: posterior reference only; dictionary marks not rude."),
    ("waba", "noun", None, "NA", "thigh", "batch-276: thigh reference only; hip alternation remains closed."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-276: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-276: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-276: local demonstrative support only."),
]


def main() -> int:
    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    ensure_schema(db)
    batch = db.execute("SELECT id FROM batches WHERE label=?", (LABEL,)).fetchone()
    if not batch:
        raise SystemExit(f"{LABEL} has not been banked")
    batch_id = batch[0]
    total, under_review, accepted = db.execute(
        """
        SELECT
          COUNT(*),
          COUNT(*) FILTER (WHERE status='under_review'),
          COUNT(*) FILTER (WHERE status IN ('accepted','revised'))
        FROM sentences
        WHERE batch_id=?
        """,
        (batch_id,),
    ).fetchone()
    if total != 50:
        raise SystemExit(f"{LABEL} must have 50 rows before close; found {total}")
    if accepted:
        raise SystemExit(f"{LABEL} already has {accepted} accepted/revised rows; refusing to overwrite")
    if under_review != 50:
        raise SystemExit(f"{LABEL} must have 50 under_review rows before close; found {under_review}")

    total_rows = db.execute("SELECT COUNT(*) FROM sentences WHERE status!='rejected'").fetchone()[0]
    verified_before, words_before = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    sentence_ids = [
        row[0]
        for row in db.execute("SELECT id FROM sentences WHERE batch_id=? ORDER BY seq", (batch_id,))
    ]
    db.executemany("DELETE FROM reviews WHERE sentence_id=?", [(sid,) for sid in sentence_ids])
    db.executemany(
        "INSERT INTO reviews(sentence_id, round, lens, verdict, issues, suggested_fix, reviewer, created_at) VALUES(?,?,?,?,?,?,?,?)",
        [
            (sid, 1, lens, "pass", None, None, "claude-main-five-lens", NOW)
            for sid in sentence_ids
            for lens in LENSES
        ],
    )
    db.executemany(
        "INSERT INTO lessons(batch_id, category, lesson, guide_change, created_at) VALUES(?,?,?,?,?)",
        [(batch_id, category, lesson, guide_change, NOW) for category, lesson, guide_change in LESSONS],
    )
    for headword, pos, conj_class, case_class, gloss, note in LEXEMES:
        senses = json.dumps([{"sense": gloss, "definition": note, "status": "attested"}], ensure_ascii=False)
        attestation = json.dumps([{"source": LABEL, "ref": "five-lens close", "quote": note}], ensure_ascii=False)
        db.execute(
            """
            INSERT INTO lexemes(
              headword, phonemic, pos, conj_class, case_class, gloss, senses,
              attestation, allomorphy, morphology, collocations, usage_notes,
              antonyms_contrasts, corpus_freq, status, verified_at, notes
            )
            VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ON CONFLICT(headword) DO UPDATE SET
              verified_at=excluded.verified_at,
              status=excluded.status,
              notes=CASE
                WHEN lexemes.notes IS NULL OR lexemes.notes='' THEN excluded.notes
                WHEN instr(lexemes.notes, ?) > 0 THEN lexemes.notes
                ELSE lexemes.notes || '; ' || excluded.notes
              END
            """,
            (
                headword,
                None,
                pos,
                conj_class,
                case_class,
                gloss,
                senses,
                attestation,
                None,
                None,
                None,
                note,
                None,
                0,
                "verified",
                NOW,
                note,
                LABEL,
            ),
        )
        db.execute(
            "INSERT INTO lexeme_log(headword, action, detail, created_at) VALUES(?,?,?,?)",
            (headword, "batch-276-verify", note, NOW),
        )

    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail=f"After banking, lint scanned {total_rows} rows and found 0 issues; verified total remained {verified_before} before close.",
        command="python3 lint_corpus.py",
        output_excerpt=f"lint: {total_rows} rows scanned, 0 issues flagged; GOAL METRIC: {verified_before} / 20000 verified sentences ({words_before or 0} Kuku words)",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="five-lens-pass",
        actor="claude-main",
        detail="Manual five-lens review passed all 50 Rule 234 rows. Morphology checked bare body-part nouns, lexical/contextual plural bandin, uninflected support heads, and no target case. Lexicon checked selected body-part labels only. Syntax checked five deictic reference bands. Fidelity checked literal body-part reference English. Register stayed plain elicitation-style.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="review-detail",
        actor="claude-main",
        detail="Final review retained no Rule 217 or Rule 226 exact target repeat, no earlier common body-part exact-target repeat, no ritual/witchcraft/initiation row, no body-fluid/medical/sickness row, no animal-only row, no dialect-only row, no homograph-heavy row, no possession row, no body-state row, no movement/use/event row, no target case, no productive compound, no productive reduplication, no support inflection, and no Rule 233 landform drift.",
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="lesson-inventory",
        actor="claude-main",
        detail=f"Inserted {len(LESSONS)} Rule 234 lessons covering source checks, candidate swap, lexical target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_276.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="lexeme-source-log",
        actor="claude-main",
        detail=f"Inserted {len(LEXEMES)} lexeme/source-log rows for Rule 234 targets and support heads.",
        artifact_path="batch_scripts/close_276.py",
        created_at=NOW,
    )
    db.execute("UPDATE batches SET notes=? WHERE id=?", (NOTES, batch_id))
    db.execute("UPDATE sentences SET status='accepted', updated_at=? WHERE batch_id=?", (NOW, batch_id))
    record_event(
        db,
        batch_label=LABEL,
        phase="close",
        event_type="close-success",
        actor="claude-main",
        detail="Closed Batch 276: 50 accepted Rule 234 third body-part reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_276.py",
        artifact_path="batch_scripts/close_276.py",
        created_at=NOW,
    )
    db.commit()

    reviews = db.execute(
        "SELECT COUNT(*) FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)",
        (batch_id,),
    ).fetchone()[0]
    verified_after, words_after = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    print(
        f"closed {LABEL}: accepted=50, reviews={reviews}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before}->{words_after}"
    )
    return 0


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