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

NOTES = (
    "LEXICAL: HEALTH, SICKNESS, INJURY, SORENESS, HEALING, AND RECOVERY (Rule 101). 50 rows. DESIGN: high-rigor "
    "medical/bodily-state lexical batch after Rule 100 direct speech. COVERED: bambay sick predicates, bambay-ma-l "
    "inchoatives, bambay-bunga-l causatives, ngulkurr-ma-l recovery, ngiki/ngikiji cough-cold states, yangka/kalbal/"
    "dukunjaka/bangkan remedy lexicon, baji/kaka/bajaybajay pain and sores, baykal transitive bite vs intransitive ache, "
    "mili burn frames, yaka/yakaji cut frames, mula blood and mula-kanga-l bleeding, julurril washing, kalji-l vomiting, "
    "wawu-wula-y exhaustion, dakwuy hunger, and two health-related direct quote/question rows. SOURCE CONTROLS: Patz "
    "medicine section; Patz examples 113, 128, 167, 216, 230, 237, 238, 247, 249-251, 394, 410, 500, 545, 556; dictionary "
    "entries for bambay, ngiki, ngikiji, yangka, kalbal, dukunjaka, bangkan, baji, kaka, bajaybajay, baykal duplicate "
    "entries, mili, yakal, wayjul/wayjuji, mula, julurril, kaljil, dakwuy, wawu-wulay; and living-book guards for "
    "kakawarri-ma-l/kakawarri-bunga-l. PROCESS STORAGE: source-pass, risk controls, banking, row inventory, lint, "
    "review, close, export, and live-doc evidence recorded in process_events and this process log. CORRECTIONS BEFORE "
    "CLOSE: no post-bank surface corrections were required by lint; manual review accepted all 50 rows as banked. "
    "Pre-close lint scanned 7247 rows with 0 issues; verified metric remained 7197 before close because the batch was "
    "under_review."
)

LESSONS = [
    ("lexicon", "`bambay` is the core sick adjective; `bambay-ma-l` means become/fall sick and `bambay-bunga-l` means make sick.", "cheatsheet Rule 101: sickness core."),
    ("syntax", "State recovery is safest with `ngulkurr-ma-l` or `kakawarri-ma-l`; do not invent a separate generic heal verb.", "cheatsheet Rule 101: recovery verbs."),
    ("lexicon", "`kakawarri-ma-l` get well and `kakawarri-bunga-l` heal are living-book licensed; `warmba` remains blocked.", "dictionary errata Batch-143: healing guard."),
    ("lexicon", "`ngiki`, `ngiki-ji`, and `ngikiji` cover cold/cough/chest complaint; `Yundu ngikiji?` is a source-shaped polar question.", "cheatsheet Rule 101: ngiki cluster."),
    ("cultural", "`yangka` green ant and `kalbal` remedy are medically specific; use them for cold/chest-sickness treatment, not as a generic modern medicine word.", "dictionary errata Batch-143: remedy specificity."),
    ("lexicon", "`dukunjaka` is bush medicine; `bangkan` is a root used as medicine for sores; these are not interchangeable generic hospital/medicine terms.", "dictionary errata Batch-143: bush-medicine terms."),
    ("lexicon", "`baji` is a sore, `kaka` is sore/achey/pain, and `bajaybajay` is painful; keep the taste/salt-water senses of `kaka` out of this batch.", "cheatsheet Rule 101: pain terms."),
    ("lexicon", "`baykal` has two distinct dictionary entries: transitive bite and intransitive ache/pain. The frame, not English gloss alone, disambiguates.", "dictionary errata Batch-143: baykal duplicate."),
    ("syntax", "`mili-bu waju-ny` and `mili-bu waju-ji-ny` cover stinging-tree/jellyfish burn frames; `mili` is not just one creature.", "cheatsheet Rule 101: burn frames."),
    ("syntax", "`yaka-l` transitive cut and `yaka-ji-y` cut oneself preserve the instrument `naybu-bu`; do not drop the reflexive suffix in self-cut rows.", "cheatsheet Rule 101: cut/reflexive."),
    ("morphology", "Bleeding is `mula-kanga-l`, explicitly not `mula-bunga-l` in Patz's causative table.", "dictionary errata Batch-143: bleeding causative."),
    ("syntax", "`julurril` is transitive wash something; `julurriji` is wash oneself. Use the transitive form for washing blood or sores.", "cheatsheet Rule 101: washing injury sites."),
    ("lexicon", "`kalji-l` vomit, `wawu-wula-y` exhausted, and `dakwuy` hungry are bodily-state controls, but they should stay secondary to the health/injury target.", "operator guide Rule 101 lexical boundary."),
    ("process", "For health or bodily-state batches, record both positive source evidence and rejected plausible medical paraphrases in `process_events`.", "operator guide Rule 101 process preservation."),
    ("source", "Patz examples can be used as close models, but generated/model-output rows and older corpus long-form rows are not source authority.", "operator guide Rule 101 source hierarchy."),
    ("orthography", "The source typo-like `dukal` in the baykal ache example is normalized to dictionary `dukul` head.", "dictionary errata Batch-143: dukul correction."),
]

LEXEMES = [
    ("bambay", "adjective", None, "NA", "sick", "batch-143: sick predicate; forms bambay-ma-l and bambay-bunga-l."),
    ("ngulkurr", "adjective", None, "NA", "good; well; not sick", "batch-143: recovery with ngulkurr-ma-l and after-sickness ngulkurr-da."),
    ("kakawarri", "adjective", None, "NA", "well; healed", "batch-143: living-book heal base; kakawarri-ma-l/get well and kakawarri-bunga-l/heal."),
    ("ngiki", "noun", None, "NA", "cold; cough; chest complaint", "batch-143: cough/cold base; ngiki-ji and ngiki-kari."),
    ("ngikiji", "noun", None, "NA", "have a cold/chest complaint", "batch-143: source question Yundu ngikiji?"),
    ("yangka", "noun", None, "neutral", "green ant", "batch-143: medicinal green ant for cold/chest complaints."),
    ("kalbal", "noun", None, "neutral", "remedy; treatment", "batch-143: remedy/treatment, especially green-ant mixture."),
    ("dukunjaka", "noun", None, "neutral", "bush medicine", "batch-143: bush medicine; not a modern hospital/medicine loan."),
    ("bangkan", "noun", None, "neutral", "root medicine for sores", "batch-143: root boiled/used to wash sores."),
    ("baji", "noun", None, "neutral", "sore", "batch-143: sore noun."),
    ("kaka", "adjective", None, "NA", "sore; achey; pain", "batch-143: bodily pain sense only."),
    ("bajaybajay", "adjective", None, "NA", "painful", "batch-143: painful/sore body expression."),
    ("baykal", "verb", "l", "NA", "bite; ache", "batch-143: duplicate-source lexeme, disambiguated by transitive bite vs intransitive ache frames."),
    ("mili", "noun", None, "neutral", "stinging tree; jellyfish", "batch-143: burn agent/instrument in waju-l/woju-ji-y frames."),
    ("wayjul", "verb-tr", "l", "NA", "burn; cook", "batch-143: waju-ny burn frame for stinging tree/jellyfish."),
    ("wayjuji", "verb-intr", "y", "NA", "be burnt; burn oneself", "batch-143: waju-ji-ny intransitive/passive burn frame."),
    ("yakal", "verb-tr", "l", "NA", "cut", "batch-143: yaka-l cut and yaka-ji-y cut oneself."),
    ("naybu", "noun", None, "neutral", "knife", "batch-143: English loan used only in source yaka-l/yaka-ji-y instrument frames."),
    ("mula", "noun", None, "neutral", "blood", "batch-143: blood noun and mula-kanga-l bleeding causative."),
    ("kangal", "verb-tr", "l", "NA", "chase; disturb; cause commotion", "batch-143: causative component in mula-kanga-l induce bleeding."),
    ("julurril", "verb-tr", "l", "NA", "wash something", "batch-143: washing sores and blood with water."),
    ("kaljil", "verb-intr", "l", "NA", "vomit", "batch-143: vomiting bodily-function rows."),
    ("wawulay", "verb-intr", "y", "NA", "be exhausted; be thirsty/tired", "batch-143: wawu-wula-y exhausted bodily state."),
    ("dakwuy", "adjective", None, "NA", "hungry", "batch-143: hungry bodily state; not old dakuy typo."),
]


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-143-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 101 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to baykal bite/ache, mula-kanga-l, ngiki/ngikiji, kakawarri healing, and burn/cut reflexives."
        ),
        artifact_path="process_logs/batch-143-health-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 143: 50 accepted health/sickness/injury rows, five-lens reviews, lessons, lexeme logs, and process evidence stored.",
        command="python3 batch_scripts/close_143.py",
        artifact_path="batch_scripts/close_143.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-143-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())
