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

NOTES = (
    "LITERAL BODY-PART REFERENCE LEXICAL EXPANSION AFTER RULE 160 (Rule 161). 50 rows. TARGETS: bajibay bone, "
    "bangkarr body, biji tail, dirra tooth, dukul head, manu throat, miyil eye, ngandal mouth, nyabil tongue, and "
    "wakuy arm. FRAMES: bare yaluy deictic identification, yinyay-supported present perception with ngayu, "
    "yaluy-supported present perception with yundu, yaluy-supported past perception with jana, and yinyay-supported "
    "present perception with ngana. REVIEW: all targets stayed bare; no target case, compounds, possession, body-state "
    "predicates, medical/healing rows, eating/butchery rows, emotion/cognition idioms, privatives, instruments, "
    "homograph drift, or animal-story event semantics."
)

LESSONS = [
    ("process", "A lexical pass can reintroduce literal body-part heads after several kin batches without opening body-state or possession grammar.", "Rule 161: lexical scope after Rule 160."),
    ("process", "Rule 161 selected only body-part heads with fresh dictionary and Patz grammar readback.", "Rule 161: source discipline."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 161: duplicate preflight."),
    ("lexicon", "`bajibay` stayed literal bone only; no boneless, want-food, or eating/butchery row.", "Rule 161: bajibay literal sense."),
    ("lexicon", "`bangkarr` stayed body only; no meat/steak, tired-body, or flesh-food drift.", "Rule 161: bangkarr literal sense."),
    ("lexicon", "`biji` stayed tail only; no fish/animal story, hooking, or cutting event row.", "Rule 161: biji literal sense."),
    ("lexicon", "`dirra` stayed tooth only; no swearing, toothless privative, or bite/eating row.", "Rule 161: dirra literal sense."),
    ("lexicon", "`dukul` stayed head only; boat, boss, tape, anger, nodding, and tantrum senses stayed closed.", "Rule 161: dukul homograph guard."),
    ("lexicon", "`manu` stayed throat only; the only/just homograph and choking/gobbling event rows stayed closed.", "Rule 161: manu homograph guard."),
    ("lexicon", "`miyil` stayed eye only; poisonous-tree homograph, blindness, literacy, cross-eye, and dusk compounds stayed closed.", "Rule 161: miyil homograph guard."),
    ("lexicon", "`ngandal` stayed mouth only; no speech, eating, or mouth-instrument row.", "Rule 161: ngandal literal sense."),
    ("lexicon", "`nyabil` stayed tongue only; no taste, speech, locative, or instrumental row.", "Rule 161: nyabil literal sense."),
    ("lexicon", "`wakuy` stayed arm only; sourced `wakuy-mbu` locative remained closed.", "Rule 161: wakuy literal sense."),
    ("morphology", "All body-part target heads stayed bare; no target LOC, DAT, ERG, INST, COMIT, POSS, PRIV, EXCESS, or compound morphology appeared.", "Rule 161: target case restraint."),
    ("morphology", "`yinyay` and `yaluy` remained support deictics only and were not attached to target heads.", "Rule 161: deictic support restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 161: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 161: perception tense forms."),
    ("syntax", "Bare deictic rows used one literal body-part target plus `yaluy` and no predicator.", "Rule 161: yaluy deictic syntax."),
    ("syntax", "`yinyay`-supported present perception rows used one bare literal body-part object plus `nyajil`.", "Rule 161: yinyay-supported perception."),
    ("syntax", "`yaluy`-supported present and past perception rows used one bare target, one support deictic, and `nyaji-l`.", "Rule 161: yaluy-supported perception."),
    ("fidelity", "English labels selected only literal source-attested body-part senses and did not add illness, possession, action, or metaphor.", "Rule 161: selected-sense fidelity."),
    ("fidelity", "The English here/there contrast follows `yaluy`/`yinyay` and does not add location-case morphology.", "Rule 161: deictic fidelity."),
    ("register", "Rows remained ordinary reference/perception statements, not medical, food-preparation, emotional, idiomatic, or narrative-event claims.", "Rule 161: register scope."),
    ("handoff", "Next cadence may return to construction consolidation, but keep body-state, possession, target case, idiom, and homograph-drift rows closed unless deliberately sourced.", "Rule 161: next cadence."),
    ("handoff", "Carry forward body-part traps: no `miyil` tree, no `dukul` boss/boat/tape, no `manu` only/just, no `bangkarr` meat drift, no privative/body-idiom compounds, and no event import.", "Rule 161: carry-forward traps."),
]

LEXEMES = [
    ("bajibay", "noun", None, "NA", "bone", "batch-203: literal bone only in deictic/perception rows; no boneless/eating/want frame."),
    ("bangkarr", "noun", None, "NA", "body", "batch-203: literal body only; no meat, steak, tiredness, or flesh-food drift."),
    ("biji", "noun", None, "NA", "tail", "batch-203: literal tail only; no fish/animal story or cutting event."),
    ("dirra", "noun", None, "NA", "tooth", "batch-203: literal tooth only; no dirra-baka, toothless, bite, or eating row."),
    ("dukul", "noun", None, "NA", "head", "batch-203: literal head only; boat/boss/tape/anger/nodding senses closed."),
    ("manu", "noun", None, "NA", "throat", "batch-203: throat only; only/just homograph and choking/gobbling events closed."),
    ("miyil", "noun", None, "NA", "eye", "batch-203: eye only; poisonous-tree homograph and eye-idiom compounds closed."),
    ("ngandal", "noun", None, "NA", "mouth", "batch-203: literal mouth only; no speech/eating/instrumental row."),
    ("nyabil", "noun", None, "NA", "tongue", "batch-203: literal tongue only; no taste/speech/case row."),
    ("wakuy", "noun", None, "NA", "arm", "batch-203: arm only; wakuy-mbu locative remained closed."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-203: retained local demonstrative in supported perception rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-203: retained local demonstrative in deictic and supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-203: retained past and nonpast perception rows with body-part objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-203: bare pronoun A in yinyay-supported perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-203: bare pronoun A in yaluy-supported perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-203: bare pronoun A in past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-203: bare pronoun A in yinyay-supported perception rows."),
]


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-203-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 161 rows. Morphology checked bare body-part targets, no target case/compound/possessive/privative/instrument/comitative forms, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked literal body-part senses and kept miyil tree, dukul boat/boss/tape, manu only/just, bangkarr meat, body-state, medical, food, and idiom traps closed. Syntax checked bare yaluy deictic identification, yinyay-supported present perception, yaluy-supported present perception, and yaluy-supported past perception. Fidelity checked no possession or event import. Register stayed ordinary.",
                 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 target locative/dative/ablative/ergative/instrument/comitative/possessive/privative/excess/compound form, no soreness/tiredness/choking/deafness/blindness, no thought/memory/emotion idiom, no eating/butchery/want/give/wash/put/cut/heal event, and no homograph 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 161 lessons covering process, literal body-part senses, homographs, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_203.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 161 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_203.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 203: 50 accepted Rule 161 literal body-part reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_203.py", artifact_path="batch_scripts/close_203.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 = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    under_review_remaining = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    lesson_count = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (batch_id,)).fetchone()[0]
    lexeme_logs = db.execute("SELECT COUNT(*) FROM lexeme_log WHERE detail LIKE '%batch-203:%'").fetchone()[0]
    process_events = db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (LABEL,)).fetchone()[0]
    print(f"closed {LABEL}: 50 accepted rows, {reviews} review passes, {lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, {process_events} process events, under_review={under_review_remaining}, verified corpus={verified}")
    return 0


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