#!/usr/bin/env python3
"""Close batch-277 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-277"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-277-body-part-construction-consolidation-after-rule234-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "BODY-PART CONSTRUCTION CONSOLIDATION AFTER RULE 234 (Rule 235). 50 rows. "
    "TARGETS retained: bandin love handles, bari chin, bibar shin, birri fingernail, jiba liver, jandal leg, "
    "jibar stomach, kangkul cheek, kuwinyu posterior, and waba thigh. SUPPORT: yinya/yaluy/yinyay plus bare "
    "nominative yundu/nyulu/ngana/jana and perception forms nyajil/nyajin. FRAMES: TARGET yinya yaluy, "
    "Yundu TARGET yinyay nyajil, Nyulu TARGET yaluy nyajil, Ngana TARGET yinyay nyajil, and "
    "Jana TARGET yaluy nyajin. REVIEW: no body-part possession, possessor pronoun, body-state, pain, illness, "
    "medical, ritual, body-fluid, animal-only, dialect-only, movement/use/event, target case, target compound, "
    "productive reduplication, pronoun case, support inflection, or homograph drift was opened."
)

LESSONS = [
    ("source", "Rule 235 retained the ten Rule 234 dictionary-backed body-part nouns and did not admit a new lexical head.", "Rule 235: retained target inventory."),
    ("source", "Patz section 3.1 supports body-part nouns as nominal corporeal objects; Rule 235 uses this as noun-domain source only.", "Rule 235: nominal source."),
    ("source", "Patz section 3.5 supplies bare nominative yundu, nyulu, ngana, and jana; Rule 235 does not open pronoun case.", "Rule 235: pronoun source."),
    ("source", "Patz section 3.7 supplies yinya, yaluy, and yinyay; Rule 235 keeps all demonstrative supports bare.", "Rule 235: demonstrative source."),
    ("source", "Patz section 3.8.3.2 lists nyaji-l 'see' as an l-conjugation perception verb; accepted corpus convention supplies nyajin for past perception.", "Rule 235: perception source."),
    ("process", "Exact duplicate preflight over all 50 planned Rule 235 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 235: duplicate preflight."),
    ("lexicon", "Bandin stayed love-handles reference only; no waist/hip, possession, body-state, or number morphology was opened.", "Rule 235: bandin."),
    ("lexicon", "Bari stayed chin only; jaw alternation remains closed.", "Rule 235: bari."),
    ("lexicon", "Bibar stayed shin only; ankle alternation remains closed.", "Rule 235: bibar."),
    ("lexicon", "Birri stayed fingernail only; toenail alternation remains closed.", "Rule 235: birri."),
    ("lexicon", "Jiba stayed liver only; jiba compounds, insides/guts, emotion, butchery, eating, and medical prose remain closed.", "Rule 235: jiba."),
    ("lexicon", "Jandal stayed leg reference only; walking, movement, injury, and possession rows remain closed.", "Rule 235: jandal."),
    ("lexicon", "Jibar stayed stomach only and remained distinct from locational jibarr 'hinterland'.", "Rule 235: jibar."),
    ("lexicon", "Kangkul stayed cheek only and remained distinct from kangku valley and kangkul kulbal 'slap someone's cheek'.", "Rule 235: kangkul."),
    ("lexicon", "Kuwinyu stayed neutral posterior reference only; no rude-register, ritual, taboo, or sitting-event row was opened.", "Rule 235: kuwinyu."),
    ("lexicon", "Waba stayed thigh only; hip alternation remains closed.", "Rule 235: waba."),
    ("morphology", "All Rule 235 target nouns stayed bare: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or target suffix.", "Rule 235: bare targets."),
    ("morphology", "Pronoun A forms stayed bare nominatives; no accusative, dative, locative, ablative, comitative, or possessive pronoun forms were admitted.", "Rule 235: bare pronouns."),
    ("morphology", "Yinya, yaluy, yinyay, nyajil, and nyajin stayed uninflected support/predicate forms; no demonstrative case or perception compound was opened.", "Rule 235: uninflected support."),
    ("syntax", "Rows 1-10 used TARGET yinya yaluy.", "Rule 235: postposed demonstrative band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yinyay nyajil.", "Rule 235: 2sg nonpast perception band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yaluy nyajil.", "Rule 235: 3sg nonpast perception band."),
    ("syntax", "Rows 31-40 used Ngana TARGET yinyay nyajil.", "Rule 235: 1pl inclusive nonpast perception band."),
    ("syntax", "Rows 41-50 used Jana TARGET yaluy nyajin.", "Rule 235: 3pl past perception band."),
    ("fidelity", "English stayed literal perception/reference prose: no possessive, medical, pain, ritual, body-fluid, movement-use, animal, or homograph claim.", "Rule 235: literal English."),
    ("register", "Rows remained plain elicitation-style clauses; posterior was retained only because the dictionary marks kuwinyu as not rude.", "Rule 235: register."),
    ("process", "Rule 217, Rule 226, earlier common body-part heads, and rejected/deferred body-part candidates stayed closed.", "Rule 235: prior target closure."),
    ("process", "The batch did not use perception frames as permission for perception compounds such as jibabu nyajil or reduplicated nyaji-l-nyaji-l.", "Rule 235: perception restraint."),
    ("process", "Rule 234 body-part lexical scope remains closed to possession/body-state/pain/illness/medical/ritual/animal-only/dialect-only/homograph/movement/event drift.", "Rule 235: carry-forward traps."),
    ("handoff", "Next batch may continue from 13,947 if this closes; do not infer body-part possession, case, pain, illness, movement, ritual, animal-only, dialect-only, homograph, or support-inflection grammar from Rule 235.", "Rule 235: next cadence."),
]

LEXEMES = [
    ("bandin", "noun", None, "NA", "love handles", "batch-277: construction consolidation only; love-handles reference/perception, no possession or state."),
    ("bari", "noun", None, "NA", "chin", "batch-277: construction consolidation only; chin, not jaw."),
    ("bibar", "noun", None, "NA", "shin", "batch-277: construction consolidation only; shin, not ankle."),
    ("birri", "noun", None, "NA", "fingernail", "batch-277: construction consolidation only; fingernail, not toenail."),
    ("jiba", "noun", None, "NA", "liver", "batch-277: construction consolidation only; liver, not jiba compounds or insides/guts."),
    ("jandal", "noun", None, "NA", "leg", "batch-277: construction consolidation only; no walking/movement row."),
    ("jibar", "noun", None, "NA", "stomach", "batch-277: construction consolidation only; not locational jibarr."),
    ("kangkul", "noun", None, "NA", "cheek", "batch-277: construction consolidation only; not kangku valley or kangkul kulbal slap."),
    ("kuwinyu", "noun", None, "NA", "posterior", "batch-277: construction consolidation only; neutral posterior reference."),
    ("waba", "noun", None, "NA", "thigh", "batch-277: construction consolidation only; thigh, not hip."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-277: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-277: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-277: local demonstrative support only."),
    ("yundu", "pronoun", None, "NA", "you singular", "batch-277: bare nominative A support only."),
    ("nyulu", "pronoun", None, "NA", "third singular", "batch-277: bare nominative A support only."),
    ("ngana", "pronoun", None, "NA", "we inclusive", "batch-277: bare nominative A support only."),
    ("jana", "pronoun", None, "NA", "they", "batch-277: bare nominative A support only."),
    ("nyajil", "verb", "l", "NA", "see", "batch-277: nonpast perception support only."),
    ("nyajin", "verb", "l", "NA", "saw", "batch-277: past perception 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-277-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 235 rows. Morphology checked bare body-part objects, bare nominative pronoun A forms, uninflected yinya/yaluy/yinyay/nyajil/nyajin, and no target case. Lexicon checked selected Rule 234 body-part senses only. Syntax checked five construction bands. Fidelity checked literal body-part reference/perception 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 possession row, no possessor pronoun row, no body-state/pain/illness/medical row, no ritual/body-fluid row, no animal-only or dialect-only row, no homograph-heavy row, no movement/use/event row, no target case, no productive compound, no productive reduplication, no pronoun case, 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 235 lessons covering source checks, lexical target senses, morphology, syntax, fidelity, register, process traps, and handoff.",
        artifact_path="batch_scripts/close_277.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 235 targets and support heads.",
        artifact_path="batch_scripts/close_277.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 277: 50 accepted Rule 235 body-part construction consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_277.py",
        artifact_path="batch_scripts/close_277.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())
