#!/usr/bin/env python3
"""Close batch-153 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-153"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "LEXICAL/FUNCTION-WORD: DISCOURSE PARTICLES, INTERJECTIONS, ANSWER WORDS, AND PRAGMATIC FUNCTION WORDS "
    "(Rule 111). 50 rows. DESIGN: closed-class particle batch after Rule 110 construction work. SOURCE CONTROLS: "
    "Patz 4.9.1 adjectival-particle complements, 4.9.2 kari/balu negation, 4.9.3 yala/nguba, 4.10 interjections, "
    "and 5.5.3 yamba/balu discourse function; dictionary checks for all listed particles and support words. "
    "PROCESS STORAGE: source pass, avoided-form controls, duplicate preflight, lint outputs, five-lens review, close, "
    "export, and live-doc verification are stored in process_events and the batch process log."
)

LESSONS = [
    ("syntax", "Nguba precedes the assumption or each alternative: nguba ... , nguba ...; do not strand it after the clause.", "Rule 111: nguba scope."),
    ("syntax", "Yala comparison takes an absolutive NP or nominative pronoun; Batch 153 avoids the insufficiently accepted Hershberger yala coordination use.", "Rule 111: yala comparison only."),
    ("syntax", "Yala-rrku is useful for 'just the same', but exact source-like surfaces collide easily; duplicate preflight matters.", "Rule 111: yala-rrku duplicate guard."),
    ("morphology", "Kari before an adjective gives ordinary negation; adjective-kari can be privative/predicator, as in ngayu kari dakuy versus ngayu dakuy-kari.", "Rule 111: kari versus -kari."),
    ("syntax", "Noun-following kari marks constituent focus contrast: jungkalu kari dumbarrin, kalka dumbarrin.", "Rule 111: kari focus."),
    ("morphology", "Kari-rrku means 'not really/not altogether'; kariku may carry not-yet temporal force. Keep both separate from plain kari.", "Rule 111: kari clitics."),
    ("syntax", "Balu is not plain negation: it covers inability/give-up, disapproval/refraining, imperatival desist/let-be, and wrong-assumption discourse uses.", "Rule 111: balu semantic split."),
    ("syntax", "Balu with a purposive complement leaves the subject in S form, unlike ordinary transitive clauses: warru balu kuni-wa-nka, dingkar balu dama-nka kuyu.", "Rule 111: balu S-subject."),
    ("fidelity", "Avoid ngawuya in new rows; this run keeps the corpus spelling guard by using kuyu in the balu spear example.", "Rule 111: ngawuya/ngawiya guard."),
    ("syntax", "Kaki stays clause-initial as if/when; kunka and nganganjirrka are precautionary/in-case discourse particles, not generic maybe synonyms.", "Rule 111: conditional/precautionary particles."),
    ("syntax", "Yamba is best kept for contrastive state/qualification frames; kari does the event-contrast and plain negation work.", "Rule 111: yamba restraint."),
    ("register", "Interjections can be complete utterances or precede a sentence with a pause; Batch 153 marks that pause with commas in yuwu/kari/kaku/ngay/yalada/yala/juyuy/wumba rows.", "Rule 111: interjection punctuation."),
    ("morphology", "Do not use yah, ba, ma, Ah, or walnga casually: the living errata flags these as special monosyllabic/attention forms needing lint and lexeme-policy work.", "Rule 111: avoided interjections."),
    ("process", "The process record for Batch 153 includes source windows, dictionary checks, avoided forms, candidate lint, duplicate replacements, lint, close, export, and public-doc verification.", "Rule 111: process-as-artifact."),
]

LEXEMES = [
    ("nguba", "particle", None, "preposed to assumption/alternative", "maybe; perhaps", "batch-153: epistemic assumption and alternative particle."),
    ("yala", "particle/interjection", None, "comparison particle; interjection OK/let's", "like; same; OK/let's", "batch-153: comparison and interjection uses; coordination excluded."),
    ("yala-rrku", "particle", None, "yala plus EMPH4", "just the same; also", "batch-153: yala-rrku same-ness rows."),
    ("kari", "particle/interjection", None, "preverbal/pre-adjectival negation; answer no", "not; no; but", "batch-153: negation, answer no, and contrast controls."),
    ("dakuy-kari", "adjective", None, "adjective plus privative -kari", "not hungry; hungerless", "batch-153: Patz ex.598b privative contrast."),
    ("binal-kari", "particle", None, "adjectival particle plus privative -kari", "not know", "batch-153: binal-kari kuku-ku row."),
    ("kari-rrku", "particle", None, "kari plus EMPH4", "not really; not altogether", "batch-153: warngku-wuna negation row."),
    ("kariku", "particle", None, "kari plus EMPH1/temporal clitic", "not yet", "batch-153: rain has not come yet row."),
    ("balu", "particle", None, "NEG2/desist/wrong-assumption particle", "desist; give up; refrain; wrong assumption", "batch-153: disapproval, let-be, inability, wrong-assumption rows."),
    ("kaki", "particle", None, "clause-initial conditional/temporal", "if; when", "batch-153: if/when rows."),
    ("kunka", "particle", None, "precautionary/in-case discourse particle", "in case; might be", "batch-153: people might talk about you."),
    ("nganganjirrka", "particle", None, "precautionary/in-case discourse particle", "just in case", "batch-153: spear/pig precautionary row."),
    ("yamba", "particle", None, "contrastive state/qualification", "but; however", "batch-153: pig did not fall and dog teeth contrast rows."),
    ("yuwu", "interjection", None, "answer word", "yes", "batch-153: affirmative answer interjection."),
    ("kaku", "interjection", None, "complete utterance or preposed with pause", "just a minute; wait for me", "batch-153: wait-for-me interjection."),
    ("ngay", "interjection", None, "conversation acknowledgement", "oh yes; I see", "batch-153: acknowledgement interjection."),
    ("yalada", "interjection", None, "conversation-closing settlement", "that's all right; settled then", "batch-153: settled-then interjection."),
    ("juyuy", "interjection", None, "dismissive interjection", "that's nonsense; take no notice", "batch-153: nonsense interjection."),
    ("wumba", "interjection", None, "never-mind interjection", "never mind", "batch-153: Patz 4.10 interjection; dictionary also has no-reason sense."),
    ("ngakiji", "verb", None, "REF -ji; PURP ngaki-ji-nka; NPST ngaki-ji", "hide", "batch-153: nguba hiding rows."),
    ("wanjabu", "interrogative", None, "where question word", "where", "batch-153: source-shaped nguba question row."),
    ("wunkuny", "temporal", None, "lexical time word", "tomorrow; next day", "batch-153: temporal nguba/kaki rows."),
    ("nyamal", "verb", None, "l-conjugation non-past", "stew; boil", "batch-153: nguba fish preparation alternative."),
    ("dindal", "verb", None, "l-conjugation non-past", "roast", "batch-153: nguba fish preparation alternative."),
    ("wawumu", "adjective", None, "dative wawumu-ku", "half-ripe", "batch-153: balu half-ripe mango row."),
    ("buymbi", "verb", None, "purposive buymbi-nka", "smoke; suck", "batch-153: balu smoking-disapproval row."),
    ("dama-nka", "verb-form", None, "purposive of dama-l", "to spear", "batch-153: balu inability/give-up row."),
    ("wajul", "verb", None, "l-conjugation non-past", "cook; boil", "batch-153: wrong-assumption roast-versus-boil row."),
    ("balka-wanji", "verb-form", None, "RECIP-PRECAUT", "might talk about", "batch-153: kunka source-shaped row."),
    ("kada-nyamunku", "verb-form", None, "dependent/precautionary source-shaped form", "might come", "batch-153: nganganjirrka source-shaped row."),
    ("dirra", "noun", None, "ABS plural/body-part noun", "teeth", "batch-153: yamba contrast state row."),
]


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-153-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 111 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to nguba preposing, yala comparison versus excluded coordination, ordinary kari "
            "versus privative -kari and cliticized kari forms, balu's non-plain-negation semantics, conditional and "
            "precautionary particles, yamba as contrastive state/qualification, and source-listed interjections with "
            "pause punctuation."
        ),
        artifact_path="process_logs/batch-153-particles-interjections-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 153: 50 accepted Rule 111 particle/interjection rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_153.py",
        artifact_path="batch_scripts/close_153.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-153-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())
