#!/usr/bin/env python3
"""Close batch-161 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-161"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-161-source-backed-narrative-support-lexicon-ii-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "LEXICAL: SOURCE-BACKED NARRATIVE SUPPORT LEXICON II (Rule 119). 50 rows. DESIGN: hand-authored rows "
    "using conservative, dictionary/grammar-backed people and kin, animals and food, camp/route/place words, "
    "sound/perception objects, weather/time supports, and already-established movement, transfer, perception, "
    "posture, sleep, and weather frames. SOURCE CONTROLS: dictionary.yaml word-entry checks plus Patz grammar "
    "noun/case tables, time/location sections, ex.38, 45-49, 57, 59, 63, 106, 109-111, 123, 127, 142-145, "
    "163-165, 271-274, 278, 297, Text 8, Text 12, and Text 14. PROCESS STORAGE: source pass, risk controls, "
    "duplicate scan, lint, five-lens review, close, export, docs, and live verification are stored."
)

LESSONS = [
    ("lexicon", "Lexical support batches can move the count safely when they reuse high-confidence source heads and keep syntax plain.", "Rule 119: conservative lexical cadence."),
    ("lexicon", "`jarramali` is primary thunder/thunderstorm/thunderheads; hearing `jarramali` is allowed only in the thunder sense.", "Rule 119: jarramali sense."),
    ("lexicon", "`kija` remains moon/month only; every row with `kija` must expose moon/month in the gloss.", "Rule 119: kija guard."),
    ("lexicon", "`dawar` is the safe star lexeme; do not relapse to earlier phantom star forms.", "Rule 119: star lexeme."),
    ("lexicon", "`badabada` and `wangkarwangkar` are lexicalized locationals; keep them solid, not hyphenated reduplications.", "Rule 119: locationals."),
    ("lexicon", "`mukirr` is safe for mussels/freshwater oyster in river-finding rows.", "Rule 119: mukirr."),
    ("lexicon", "`bilngkumu`, `jarba`, and `kadar` are safe animal heads when the row keeps the English scope simple.", "Rule 119: animal heads."),
    ("lexicon", "`mayi kaya-nga` follows Patz's possessive table for dog's food; do not invent a possessive particle.", "Rule 119: possessive food."),
    ("morphology", "Common-noun A with `nyaji-l` still takes ERG; pronoun A remains unmarked.", "Rule 119: perception A marking."),
    ("morphology", "`babaji-y` askers remain ABS/S; person asked is LOC:pt and inanimate topic is DAT.", "Rule 119: ask-about frame."),
    ("morphology", "Laugh targets stay DAT:pt, e.g. `karrkay-anka` and `nganjan-anka`.", "Rule 119: laugh target."),
    ("morphology", "`wunanay` is the reduced nonpast/stative form; `wunanan` is the past rest/sleep form already normalized in the corpus.", "Rule 119: posture reduction."),
    ("morphology", "`bundanday` is the reduced nonpast/stative stay form; do not force full reduplication in the surface.", "Rule 119: posture reduction."),
    ("syntax", "Movement rows remain safest with one explicit source or goal rather than stacked directionals.", "Rule 119: motion scope."),
    ("syntax", "Transitive rows in a lexical batch still need overt objects: get, cook, eat, put, close, give, take, make, hear/see, and find.", "Rule 119: object visibility."),
    ("syntax", "Comitative rows use sourced forms such as `nganjan-anji` and `jawun-unji`; do not analogize unsourced comitative allomorphs.", "Rule 119: comitative forms."),
    ("fidelity", "If a Kuku row is semantically plain, keep the English plain; do not inflate lexical support rows into richer English narratives.", "Rule 119: English follows Kuku."),
    ("register", "Short source-clear rows are acceptable in this lexical support batch because the goal is verified lexical variation, not new discourse machinery.", "Rule 119: register scope."),
    ("process", "A green mechanical lint is not a lexical source check; the source pass must still name dictionary and grammar evidence.", "Rule 119: source evidence."),
    ("process", "Under-review batches can be accepted with no repairs, but the no-repair result still needs an explicit five-lens review event.", "Rule 119: review evidence."),
]

LEXEMES = [
    ("maral", "noun", None, "ERG maral-angka; LOC:pt maral-anda", "girl", "batch-161: girl participant in perception/ask/motion rows."),
    ("warru", "noun", None, "ERG warru-ngku", "young man", "batch-161: young man A in get/make rows."),
    ("ngawa", "noun", None, "NA", "baby", "batch-161: baby sleep/wake rows."),
    ("yaba", "noun", None, "LOC:pt yaba-nda", "elder brother", "batch-161: ask-about addressee."),
    ("bilngkumu", "noun", None, "NA", "crocodile", "batch-161: river-source motion row."),
    ("jarba", "noun", None, "NA", "snake", "batch-161: under-tree location and perception object."),
    ("kadar", "noun", None, "NA", "wallaby", "batch-161: road motion row."),
    ("mukirr", "noun", None, "LOC:pt mukirr-anda", "freshwater oyster; mussel", "batch-161: river finding object."),
    ("minya", "noun", None, "DAT minya-ka", "meat; edible animal food", "batch-161: eating rows."),
    ("kambi", "noun", None, "COMIT kambi-ji", "clothes", "batch-161: transfer object."),
    ("kulji", "noun", None, "LOC kulji-nga", "stone; rock", "batch-161: put/get/find object."),
    ("badabada", "locational", None, "ABESS badabada-mundu", "down there; underneath", "batch-161: solid lexicalized locational."),
    ("wangkarwangkar", "locational", None, "NA", "up there; above", "batch-161: solid lexicalized locational."),
    ("yinyay", "demonstrative/location", None, "LOC yinyay-mba", "there", "batch-161: there-LOC rows."),
    ("wujurr-bu", "case-form", None, "LOC", "at/during the night", "batch-161: night-time perception/calling rows."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-161: sourced comitative form."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-161: sourced comitative form."),
    ("mayi kaya-nga", "possessive-np", None, "POSS.ABS", "the dog's food", "batch-161: Patz possessive table form."),
    ("jarramali", "noun", None, "NA", "thunder; thunderstorm", "batch-161: heard thunder and weather-event rows."),
    ("dawar", "noun", None, "NA", "star", "batch-161: star perception row."),
    ("kija", "noun", None, "NA", "moon; month", "batch-161: moon-only guard row."),
    ("wungar", "noun", None, "NA", "sun; day", "batch-161: sun-above phrase."),
    ("nyiku", "time-word", None, "NA", "today; now", "batch-161: weather-time row."),
    ("yilayku", "time-word", None, "NA", "yesterday", "batch-161: weather-time row."),
    ("wunkuny", "time-word", None, "NA", "tomorrow; next day", "batch-161: future weather row."),
    ("yilay-yilay", "time-word", None, "NA", "late afternoon", "batch-161: source-checked for forward use."),
    ("balkal", "transitive-verb", "l", "NA", "speak; tell; make", "batch-161: speech and make rows."),
    ("babaji", "intransitive-verb", "y", "NA", "ask", "batch-161: fixed-intransitive ask-about rows."),
    ("nyajil", "transitive-verb", "l", "NA", "see; hear", "batch-161: perception rows with A marking checked."),
    ("milka-janay", "intransitive-verb", "y", "NA", "listen", "batch-161: concrete listening row."),
    ("yajarril", "interaction-verb", "y/l", "NA", "laugh", "batch-161: DAT:pt target rows."),
    ("warrmba-bungal", "transitive-verb", "l", "NA", "find", "batch-161: overt found-object rows."),
    ("wajul", "transitive-verb", "l", "NA", "cook; burn", "batch-161: food-cooking row."),
    ("nukal", "transitive-verb", "l", "NA", "eat; drink", "batch-161: meat-eating rows."),
    ("manil", "transitive-verb", "l", "NA", "get", "batch-161: object-getting rows."),
    ("yijarril", "transitive-verb", "l", "NA", "put; place", "batch-161: object-placement rows."),
    ("nandal", "transitive-verb", "l", "NA", "close; cover", "batch-161: house-close row."),
    ("kidal", "transitive-verb", "l", "NA", "sweep; wipe; remove", "batch-161: ground-sweep row."),
    ("yirrkay", "intransitive-verb", "y", "NA", "call out", "batch-161: night call-out row."),
    ("warngku wunay", "intransitive-verb", "y", "NA", "sleep", "batch-161: baby sleep row."),
    ("wunay", "intransitive-verb", "y", "NA", "lie down; rest", "batch-161: reduced wunanay/wunanan rows."),
    ("bunday", "intransitive-verb", "y", "NA", "sit; stay", "batch-161: reduced bundanday stay row."),
    ("wandil", "intransitive-verb", "l", "NA", "wake; get up; come out", "batch-161: baby wake row."),
    ("wundil", "transitive-verb", "l", "NA", "bring; take", "batch-161: object plus source/goal rows."),
    ("kaday", "intransitive-verb", "y", "NA", "come", "batch-161: motion/weather rows."),
    ("dungay", "intransitive-verb", "y", "NA", "go", "batch-161: motion/comitative 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}")

    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-161-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 119 rows with no row repairs required. Morphology checked "
            "ERG/ABS marking, LOC/DAT/ABL/ABESS/COMIT/POSS forms, reduced posture surfaces, past/nonpast alignment, "
            "and DAT:pt laugh targets. Lexicon checked each content head against dictionary.yaml and Patz. Syntax "
            "checked overt objects, fixed-intransitive babaji-y, comitative forms, source/goal scope, and weather/time "
            "predicates. Fidelity kept English plain and source-aligned. Register stayed practical narrative-style "
            "pending elder verification."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="review-detail",
        actor="claude-main",
        detail=(
            "No repairs were needed during Batch 161 five-lens review. Explicit retained decisions: jarramali glossed "
            "as thunder where heard, kija glossed as moon, badabada/wangkarwangkar kept solid, no yunga-l rows, "
            "no ergative babaji-y askers, ERG common-noun perceivers with nyaji-l, and DAT:pt laugh targets."
        ),
        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 119 lessons covering lexical scope, morphology, syntax, fidelity, register, and process safeguards.",
        artifact_path="batch_scripts/close_161.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 119 source-backed narrative support vocabulary and forms.",
        artifact_path="batch_scripts/close_161.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 161: 50 accepted Rule 119 lexical-support rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_161.py",
        artifact_path="batch_scripts/close_161.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 action='batch-161-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, under_review={under_review_remaining}, "
        f"verified corpus={verified}"
    )
    return 0


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