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

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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

NOTES = (
    "LEXICAL: PERCEPTION, ATTENTION, SEARCHING, AND FINDING VERBS (Rule 97). 50 rows. DESIGN: lexical-control batch "
    "after Rule 96 construction work. COVERED: `nyajil` general see/hear/perceive; explicit `milkabu nyajil` hear; "
    "`milka-janay` listen; `milka-kari`/`milka dudu` deaf/cannot-hear; `miyil-janay` look/watch; `miyil-dandi` stare; "
    "`manubu-damal` watch/guard; `warringal` observe; `walu-wukurril` look around; `kurrka-nyaji-ji` look back; "
    "`binal` know; `milka-dalkay` remember; `milka-wulay` forget; `milkabu manil` remember/recollect; `nubil` seek; "
    "`nubiji` be lost; `nubi-manil` lose; `warrmba-bungal` find; `babal` try/taste; `nyumal` smell/taste; `jila`, "
    "`nganjay`, and `nganja-burra` smell/taste nouns/adjectives. SOURCE CAUTIONS: `ngara` blocked for hear; no Nyungkul "
    "`ngunnga-bungal`; no speculative recognise rows; no exact Ah/Yah attention interjections. Duplicate guard forced "
    "three replacements before banking; manual review replaced inanimate `kalka-nka` with animate `karrkay-nka` in the "
    "`milka-wulay` row. Pre-close lint scanned 7047 rows with 0 issues; verified metric remained 6997 before close."
)

LESSONS = [
    ("lexicon", "`nyajil` is the general perception verb for see/hear/perceive; add `milkabu` only when hearing must be explicit.", "cheatsheet Rule 97: nyajil."),
    ("lexicon", "`milkabu nyajil` is the safe explicit hear construction; `ngara` remains blocked for hear/listen.", "dictionary errata: ngara blocked."),
    ("lexicon", "`milka-janay` means listen/obey, while `miyil-janay` means look/watch; do not collapse ear and eye compounds.", "cheatsheet Rule 97: ear/eye compounds."),
    ("lexicon", "`milka-kari` and `milka dudu` both support cannot-hear/deaf meanings, with different morphology.", "cheatsheet Rule 97: deaf/cannot-hear."),
    ("lexicon", "`manubu-damal`, `warringal`, `walu-wukurril`, and `kurrka-nyaji-ji` cover different watch/look-around/look-back meanings.", "cheatsheet Rule 97: watch/look family."),
    ("lexicon", "`binal` know is source-backed with `binal kari` and `binal-binalku bundanka` examples.", "cheatsheet Rule 97: binal."),
    ("lexicon", "`milka-dalkay`, `milka-wulay`, and `milkabu manil` are separate remember/forget/recollect entries.", "cheatsheet Rule 97: memory idioms."),
    ("lexicon", "`nubil`, `nubiji`, `nubi-manil`, and `warrmba-bungal` must stay distinct: seek, be lost, lose, find.", "cheatsheet Rule 97: search/find/lose."),
    ("lexicon", "`babal` try/taste and `nyumal` smell/taste overlap in English but are separate dictionary entries.", "cheatsheet Rule 97: taste/smell."),
    ("lexicon", "`nganjay` is no-good/bad-smell while `nganja-burra` is bad taste; do not merge smell and taste nouns.", "dictionary errata: smell/taste split."),
    ("morphology", "Do not put inanimate nouns into potent dative by analogy; the review replaced `kalka-nka` with animate `karrkay-nka`.", "operator guide: case review after lint."),
    ("process", "Duplicate checks are part of linguistic quality: source-exact examples must still be varied if already in the corpus.", "operator guide: duplicate guard."),
]

LEXEMES = [
    ("nyajil", "verb-tr", "l", "NA", "perceive; see; hear", "batch-139: general perception verb."),
    ("milkabu nyajil", "verb-tr", "l", "NA", "hear", "batch-139: explicit hearing construction."),
    ("milka-janay", "verb-intr", "y", "NA", "listen; obey", "batch-139: listen/obey ear compound."),
    ("milka-kari", "adjective", None, "NA", "cannot hear; deaf", "batch-139: privative hearing adjective."),
    ("milka dudu", "adjective", None, "NA", "deaf; stubborn", "batch-139: deaf/stubborn attribute."),
    ("miyil-janay", "verb-intr", "y", "NA", "look; watch", "batch-139: eye-based look/watch."),
    ("miyil-dandi", "adjective", None, "NA", "stare; look hard; concentrate", "batch-139: eye-hard attribute."),
    ("manubu-damal", "verb-tr", "l", "NA", "watch; guard", "batch-139: watch/guard rows."),
    ("warringal", "verb-tr", "l", "NA", "observe; watch where someone goes", "batch-139: observe row."),
    ("walu-wukurril", "verb-tr", "l", "NA", "look around", "batch-139: look-around row."),
    ("kurrka-nyaji-ji", "verb-intr", "intransitivized", "NA", "look back", "batch-139: Patz text 3 look-back verb."),
    ("binal", "verb-tr", None, "NA", "know", "batch-139: know rows."),
    ("milka-dalkay", "verb-intr", "y", "NA", "remember", "batch-139: remember rows."),
    ("milka-wulay", "verb-intr", "y", "NA", "forget; forgive", "batch-139: forget row."),
    ("milkabu manil", "verb-tr", "l", "NA", "remember; recollect", "batch-139: recollect row."),
    ("nubil", "verb-tr", "l", "NA", "seek; look for", "batch-139: seek/search rows."),
    ("nubiji", "verb-intr", "intransitivized", "NA", "be looked for; be lost", "batch-139: lost row."),
    ("nubi-manil", "verb-tr", "l", "NA", "lose", "batch-139: lose rows."),
    ("warrmba-bungal", "verb-tr", "l", "NA", "find", "batch-139: Yalanji find rows."),
    ("babal", "verb-tr", "l", "NA", "try; taste", "batch-139: try/taste rows."),
    ("nyumal", "verb-tr", "l", "NA", "smell; taste", "batch-139: smell/taste rows."),
    ("jila", "noun", None, "neutral", "smell", "batch-139: source strong-smell row."),
    ("nganjay", "adjective", None, "NA", "no good; wilted; bad smell", "batch-139: bad-smell warning row."),
    ("nganja-burra", "noun", None, "NA", "bad taste", "batch-139: bad-taste row."),
]


def main() -> int:
    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    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-139-verify", note, 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))
    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-139-verify'").fetchone()[0]
    print(
        f"closed {LABEL}: 50 accepted rows, {reviews} review passes, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, verified corpus={verified}"
    )
    return 0


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