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

NOTES = (
    "LEXICAL: EVENT NOUNS, SOUND/ACTION NOUNS, AND TEMPORAL-REFERENCE LEXICON (Rule 115). 50 rows. DESIGN: "
    "hand-authored lexical reinforcement following Rule 114, using only source-backed event/time/sound/weather nouns "
    "and conservative prior-event forms. SOURCE CONTROLS: Patz 3.4, 3.10.1, 4.4.4.3, 5.2.2; examples 491-497 and "
    "635-636; dictionary checks for time, sound, song, speech, rain, wind, and thunderstorm nouns. PROCESS STORAGE: "
    "source inventory, exclusions, exact-surface scan, static guards, lint pass, five-lens review, close, export, docs, "
    "and live-route verification are stored."
)

LESSONS = [
    ("lexicon", "Event-noun batches should privilege Patz-supplied event nouns and object ablatives over English-style action nouns.", "Rule 115: event noun source discipline."),
    ("syntax", "Prior-event `wawu-` rows require an ablative `-muny` form; a bare `wawu-` sequence is incomplete.", "Rule 115: wawu ablative guard."),
    ("syntax", "Use `wawu-jilba-muny` and `wawu-ngangkurr-muny` where Patz says the nominal event is preferred; do not force verb + `-nya-muny`.", "Rule 115: nominal prior event preference."),
    ("syntax", "`wawu-warngku-muny` is a sourced bridge for after a sleep; it should not be replaced by an invented sleep-verb prior-event form.", "Rule 115: sleep event noun."),
    ("lexicon", "`mayi` can support the meal event in `wawu-mayi-muny`, but ordinary food rows should still gloss it as food unless the construction supplies meal sense.", "Rule 115: mayi meal/food distinction."),
    ("lexicon", "`kambi` in `wawu-kambi-muny julurrin` is the object attracting the ablative in a clothes-washing event.", "Rule 115: object ablative event."),
    ("lexicon", "`jukijuki` can appear in the source-shaped feeding construction `wawu-jukijuki-muny mayi dajin`; avoid generalizing it into arbitrary after-chicken events.", "Rule 115: feeding event limit."),
    ("lexicon", "`nyiku`, `wunkuny`, `yilayku`, `yilay-yilay`, and `wunkuwingku` are time references; they do not need extra English adverbial morphology.", "Rule 115: time-word root use."),
    ("morphology", "`muduwajuny` is a sourced daybreak time form; keep the final `-ny` because this is a lexical/time form, not leaked verbal past.", "Rule 115: muduwajuny lexical -ny."),
    ("morphology", "`wujurr-bu` is the sourced night locative; avoid analogical `wujurr-ba` in new rows.", "Rule 115: wujurr-bu locative."),
    ("lexicon", "`kija` is only moon/month in the current grammar/dictionary basis; never use it for cold.", "Rule 115: kija moon/month only."),
    ("lexicon", "`wungar dakal`, `wungar daray`, and `wungar wangkar-wangkar` are time-of-day phrases, not free templates for arbitrary sun compounds.", "Rule 115: sun phrase limits."),
    ("lexicon", "`wulngku` is the safer song noun; `burri` remains excluded from new rows until its thin dictionary status is resolved.", "Rule 115: song noun choice."),
    ("lexicon", "`ngangkurr` is a barking sound noun; source-backed rows can treat it as a heard or coming sound without inventing a new action noun.", "Rule 115: barking noun."),
    ("lexicon", "`kuku` can mean news/talk/language/words; rows must make the intended sense clear in English and analysis.", "Rule 115: kuku sense clarity."),
    ("fidelity", "Translate `wunkuny` as next day/tomorrow and `yilayku` as yesterday; do not over-specify tense beyond the Kuku predicate.", "Rule 115: temporal English."),
    ("fidelity", "Weather nouns such as `kaba`, `muyar`, and `jarramali` should stay in simple source-backed come/fall/not-come frames unless a stronger source is present.", "Rule 115: weather frame discipline."),
    ("process", "For lexical batches, store both the included inventory and the excluded/risky inventory so later operators know why tempting words were not used.", "Rule 115: process inventory."),
    ("process", "A green under-review lint pass does not close a batch; five-lens review and explicit close remain required before the goal metric advances.", "Rule 115: close discipline."),
]

LEXEMES = [
    ("wawu-warngku-muny", "case-form", None, "TEMP4-sleep-ABL", "after the sleep", "batch-157: Patz ex.635 source bridge."),
    ("wawu-mayi-muny", "case-form", None, "TEMP4-food-ABL", "after the meal", "batch-157: reinforced Patz 3.10.1 meal event."),
    ("wawu-jilba-muny", "case-form", None, "TEMP4-walk-ABL", "after the walk", "batch-157: nominal prior-event preference."),
    ("wawu-ngangkurr-muny", "case-form", None, "TEMP4-barking.noise-ABL", "after the barking", "batch-157: nominal prior-event preference."),
    ("wawu-kambi-muny", "case-form", None, "TEMP4-clothes-ABL", "after washing clothes", "batch-157: object-ablative event."),
    ("wawu-jukijuki-muny", "case-form", None, "TEMP4-chicken-ABL", "after feeding chickens", "batch-157: source-shaped feeding event."),
    ("wawu-yinya-muny", "case-form", None, "TEMP4-that-ABL", "after that; since then", "batch-157: general temporal bridge."),
    ("nyiku", "temporal", None, "root time word", "now; today", "batch-157: Patz 3.4 time-word root."),
    ("wunkuny", "temporal", None, "root time word", "next day; tomorrow", "batch-157: Patz 3.4 time-word root."),
    ("yilayku", "temporal", None, "root time word", "yesterday", "batch-157: Patz 3.4 time-word root."),
    ("yilay-yilay", "temporal", None, "full reduplication", "late afternoon", "batch-157: Patz/dictionary time word."),
    ("wunkuwingku", "temporal", None, "root time word", "morning", "batch-157: dictionary time word."),
    ("muduwajuny", "temporal", None, "muduwaju-ny", "at daybreak", "batch-157: Patz/dictionary daybreak form."),
    ("kunarangkal", "temporal", None, "root time word", "middle of the night", "batch-157: dictionary time word."),
    ("ngadiku", "temporal", None, "ngadi-ku", "long ago", "batch-157: Patz 3.4 inflected time root."),
    ("wujurr-bu", "case-form", None, "night-LOC", "during the night", "batch-157: Patz 3.4 common time noun."),
    ("warngku", "noun", None, "time/event noun", "sleep; one day and night", "batch-157: source event noun in wawu-warngku-muny."),
    ("kija", "noun", None, "moon/month noun", "moon; month", "batch-157: kija kept to moon/month semantics."),
    ("wungar dakal", "time-phrase", None, "sun climb", "sunrise", "batch-157: sourced descriptive time phrase."),
    ("wungar daray", "time-phrase", None, "sun fall", "sunset", "batch-157: dictionary time phrase."),
    ("wungar wangkar-wangkar", "time-phrase", None, "sun above-REDUP", "midday", "batch-157: sourced descriptive time phrase."),
    ("wungar-iji", "temporal", None, "sun-COMIT", "hot season", "batch-157: Patz common time noun."),
    ("bulur-iji", "temporal", None, "cold-COMIT", "cold season", "batch-157: Patz common time noun."),
    ("wulngku", "noun", None, "song noun", "song", "batch-157: dictionary-backed song noun."),
    ("wulngku badi", "intransitive-verb", None, "song cry/sing", "sing", "batch-157: dictionary-backed singing expression."),
    ("badi", "intransitive-verb", None, "past badi-ny", "cry; sing; wail", "batch-157: source example child cried for food."),
    ("banbadi", "verb-form", None, "elder surface of banbadi-y", "cry repeatedly", "batch-157: repeated crying form with -iy surface drop."),
    ("ngangkurr", "noun", None, "sound noun", "barking noise", "batch-157: barking sound noun."),
    ("kuku", "noun", None, "speech/news noun", "news; talk; language; words", "batch-157: speech/news noun."),
    ("jarramali", "noun", None, "weather noun", "thunder; thunderstorm", "batch-157: weather event noun."),
    ("kaba", "noun", None, "weather noun", "rain", "batch-157: rain noun in fall/come frames."),
    ("muyar", "noun", None, "weather noun", "wind", "batch-157: wind noun in come/source frames."),
    ("wungar", "noun", None, "celestial noun", "sun", "batch-157: base for time-of-day phrases."),
    ("mukul-bama", "noun", None, "compound", "old people", "batch-157: speech/song knowledge rows."),
    ("babajil", "transitive-verb", "l", "past babaji-ny", "ask", "batch-157: ask about song row."),
    ("yungal", "transitive-verb", "l", "past yunga-ny", "send", "batch-157: send news 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-157-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 115 rows. Morphology checked -muny, lexical -ny in "
            "muduwajuny/wunkuny, wujurr-bu, -iy surface drop in banbadi, past/nonpast surfaces, and moon/month "
            "kija guard. Lexicon checked each content word against Patz/dictionary. Syntax checked time-word use, "
            "nominal prior events, and simple weather/sound frames. Fidelity checked English temporal/event readings. "
            "Register kept rows practical and conservative 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=(
            "Rejected-risk decisions retained: no new arbitrary action nominalizations; no unsourced wawu-VERB-nya-muny; "
            "no kija=cold; no burri sentence rows; no abstract 'event' metawords. Accepted rows are lexical support for "
            "later sequencing batches, not a claim that every verb can be nominalized."
        ),
        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 115 lessons covering event nouns, time words, wawu nominal ablatives, sound/weather nouns, and process-capture discipline.",
        artifact_path="batch_scripts/close_157.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 115 event, temporal, sound, speech, song, and weather lexicon.",
        artifact_path="batch_scripts/close_157.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 157: 50 accepted Rule 115 lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_157.py",
        artifact_path="batch_scripts/close_157.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-157-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())
