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

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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-144"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "CONSTRUCTION: BODY-PART AND BODILY-STATE ARGUMENT STRUCTURE (Rule 102). 50 rows. DESIGN: follow Rule 101 "
    "health lexicon with a syntactic batch focused on whole-part apposition, affected body-part objects/locatives, "
    "body-part instruments, reflexive/passive injury alternations, chance-passive stepping, and comitative/privative "
    "bodily states. COVERED: no-possessive inalienable apposition; same-case locative whole+part NPs; body-part "
    "objects with bite/wash/step-on frames; mara-bu/jina-bu/bungku-bu/milka-bu/miyil-bu/dirra-bu/ngandal-bu "
    "instruments; yaka-ji, baka-ji, yirrba-n-yirrba-ji, junka-ji, kuni-ji, bayka-ji, waju-ji passives/reflexives; "
    "kuli-ji, kumbu-ji, ngiki-ji, ngiki-kari, dirra-kari, milka-kari; muku kaka causal frames. SOURCE CONTROLS: "
    "Patz 4.5.2; 4.1.4.4 examples 243-252; 4.2.4.2 examples 337-344; 4.2.4.3 examples 345-351; 4.6 examples "
    "531-557; dictionary entries for body parts and injury/state lexemes. PROCESS STORAGE: source-pass, risk "
    "controls, row inventory, lint outputs, review, close, export, and live-doc verification are stored in process_events "
    "and the batch process log. CORRECTIONS BEFORE CLOSE: close script records the post-bank review result; any lint "
    "or duplicate corrections are documented in the process log before final acceptance."
)

LESSONS = [
    ("syntax", "Inalienable body-part possession normally uses whole + part apposition without possessive -mu.", "cheatsheet Rule 102: body-part apposition."),
    ("syntax", "In whole-part locative NPs, the whole and body part share case: karrkay-anda mara-nga, babi-nda mara-nga.", "cheatsheet Rule 102: same-case body-part NPs."),
    ("morphology", "Y-final body parts take y-final locative allomorphs such as wakuy-mbu; do not write wakuy-nga.", "dictionary errata Batch-144: y-final locative guard."),
    ("syntax", "Body-part instruments remain instrumental even inside reflexive/passive frames.", "cheatsheet Rule 102: instrumental persistence."),
    ("syntax", "Chance passive uses a locative agent plus -ji- verb and is not the same construction as transitive kanban 'by mistake'.", "cheatsheet Rule 102: chance passive versus kanban."),
    ("syntax", "Affected body parts can appear as absolutive parts in reflexive frames, e.g. jina baka-ji-ny and yimbi junka-ji-y.", "cheatsheet Rule 102: affected body part in reflexive."),
    ("lexicon", "`dukul` remains the head word for head; `dukal` is not allowed.", "dictionary errata Batch-144: dukul guard."),
    ("lexicon", "`wubul` is avoided for heart because the quantifier many/all sense dominates; this batch uses bangkarr for body/flesh.", "dictionary errata Batch-144: wubul heart guard."),
    ("syntax", "Hearing rows use `nyaji-l` with optional `milka-bu`; never revive `ngara-l` as hear.", "cheatsheet Rule 102: hearing with milka-bu."),
    ("syntax", "`kuli-ji`, `kumbu-ji`, and `ngiki-ji` are comitative state predicates, not possessive clauses.", "cheatsheet Rule 102: comitative bodily states."),
    ("syntax", "`ngiki-kari`, `dirra-kari`, and `milka-kari` are privative state predicates; translate by state, not by a literal ownership clause.", "cheatsheet Rule 102: privative bodily states."),
    ("source", "Grammar examples can be close models, but older synthetic narrative rows are not source authority for new body-part syntax.", "operator guide Rule 102 source hierarchy."),
    ("process", "Construction batches should log both accepted patterns and blocked near-patterns because case marking is the main failure mode.", "operator guide process storage."),
]

LEXEMES = [
    ("dukul", "noun", None, "neutral", "head", "batch-144: body-part apposition; guard against dukal typo."),
    ("mungka", "noun", None, "neutral", "hair", "batch-144: inalienable body-part apposition."),
    ("walu", "noun", None, "neutral", "face", "batch-144: affected body-part object and predicate."),
    ("miyil", "noun", None, "neutral", "eye", "batch-144: eye as body part and instrument."),
    ("milka", "noun", None, "neutral", "ear", "batch-144: ear instrument and privative milka-kari."),
    ("ngandal", "noun", None, "neutral", "mouth", "batch-144: mouth as body part and instrument."),
    ("dirra", "noun", None, "neutral", "tooth; teeth", "batch-144: teeth as body part, instrument, and privative dirra-kari."),
    ("mara", "noun", None, "neutral", "hand", "batch-144: body-part apposition, locative affected part, and instrument mara-bu."),
    ("jina", "noun", None, "neutral", "foot; track", "batch-144: foot body part, track object, and instrument jina-bu."),
    ("durru", "noun", None, "neutral", "toe", "batch-144: affected body part in bite frame."),
    ("wakuy", "noun", None, "neutral", "arm", "batch-144: y-final locative wakuy-mbu in accidental reflexive."),
    ("muku", "noun", None, "neutral", "back", "batch-144: sore-back apposition and causal frames."),
    ("bangkarr", "noun", None, "neutral", "body; flesh", "batch-144: body-state predicate and tired-body conditional."),
    ("bungku", "noun", None, "neutral", "knee", "batch-144: grammar-sourced knee instrument bungku-bu."),
    ("yimbi", "noun", None, "neutral", "lips", "batch-144: grammar-sourced yimbi junka-ji-y."),
    ("kumbu", "noun", None, "neutral", "urine", "batch-144: kumbu-ji bodily state."),
    ("kuli", "noun", None, "neutral", "rage; anger", "batch-144: kuli-ji vicious/rage-with state."),
    ("narri-l", "verb-tr", "l", "NA", "step on", "batch-144: chance passive narri-ji-ny with body part."),
    ("yijarril", "verb-tr", "l", "NA", "put", "batch-144: put onto/in body-part locative."),
    ("yirrbal", "verb-tr", "l", "NA", "scratch", "batch-144: yirrba-n-yirrba-ji reflexive scratch."),
    ("jungal", "verb-tr", "l", "NA", "paint", "batch-144: junka-ji-y paint lips."),
    ("murraja", "noun", None, "potent", "stonefish", "batch-144: passive/agentive injury frame."),
    ("yaburr", "noun", None, "potent", "shark", "batch-144: passive bite frame yaburr-undu bayka-ji-ny."),
]


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}")

    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-144-verify", note, 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 102 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to whole+part same-case locatives, body-part instruments, reflexive/passive -ji-, "
            "chance passive versus kanban, and comitative/privative state predicates."
        ),
        artifact_path="process_logs/batch-144-body-state-process.md",
        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 144: 50 accepted body-part/body-state construction rows, five-lens reviews, lessons, lexeme logs, and process evidence stored.",
        command="python3 batch_scripts/close_144.py",
        artifact_path="batch_scripts/close_144.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]
    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 action='batch-144-verify'").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, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, "
        f"{process_events} process events, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
