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

NOTES = (
    "LEXICAL: MATERIAL AND LANDSCAPE EXPANSION AFTER RULE 128 (Rule 129). 50 rows. DESIGN: hand-authored "
    "source-backed expansion for birra leaf, dumbul bark, kubu smoke, kulji stone/rock, jukar sand, manjal "
    "mountain, madja scrub/rainforest, diburr seed, nganka flower, and ngurrbal fog, then drilled through old "
    "rest, placement, transfer, perception, ask-about, laugh-target, and closed-comitative frames. SOURCE "
    "CONTROLS: exact dictionary/grammar/lexeme readback; weak warrur evidence excluded; no generator-authored "
    "rows; no new instrument, comitative, possessive, or abstract case analogy. REVIEW: birra not lungs, dumbul "
    "bark only, diburr seed only, kulji not mountain, manjal mountain, common-noun nyaji-l A ERG, pronoun A bare, "
    "babaji-y askers not ERG-marked, yajarri-l targets DAT:pt, comitatives closed."
)

LESSONS = [
    ("process", "A lexical batch should prefer a small fully sourced set over a larger weakly sourced list.", "Rule 129: lexical source discipline."),
    ("process", "Weakly evidenced heads can be explicitly excluded and logged; Batch 171 deferred `warrur` rather than forcing it.", "Rule 129: exclusion logging."),
    ("process", "Exact duplicate scanning before banking remains mandatory even when every row looks newly authored.", "Rule 129: duplicate scan."),
    ("process", "Source readback must include existing lexeme table status as well as dictionary and grammar evidence.", "Rule 129: three-source readback."),
    ("lexicon", "`birra` is leaf in this batch; the dictionary lungs sense is excluded.", "Rule 129: birra sense."),
    ("lexicon", "`dumbul` can mean bark/hard covering; Batch 171 uses only bark.", "Rule 129: dumbul sense."),
    ("lexicon", "`diburr` can mean seed, egg, bullet, or tablets; Batch 171 uses only the seed sense.", "Rule 129: diburr sense."),
    ("lexicon", "`kulji` is stone/rock/pebbles and explicitly not mountain; mountain is `manjal`.", "Rule 129: kulji/manjal contrast."),
    ("lexicon", "`jukar`, `madja`, `nganka`, `ngurrbal`, and `kubu` remain sand, scrub/rainforest, flower, fog, and smoke.", "Rule 129: material/landscape set."),
    ("morphology", "No `kulji-bu` or other instrument row was admitted; lexical expansion does not license productive instrument analogy.", "Rule 129: no new instruments."),
    ("morphology", "`manjal-ba`, `madja-nga`, `juku-ngu`, `bana-nga`, `ngalkal-ba`, and `baral-ba` remain LOC forms with honest glossing.", "Rule 129: locative honesty."),
    ("morphology", "`bayan-ka` and `bayan-muny` remain the controlled transfer goal/source forms.", "Rule 129: transfer cases."),
    ("morphology", "The closed comitative set remains `ngawa-nji`, `jawun-unji`, `nganjan-anji`, `juku-ji`, and `kambi-ji`.", "Rule 129: closed comitatives."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked across smoke, leaf, bark, stone, mountain, and seed/flower/fog rows.", "Rule 129: perception A marking."),
    ("syntax", "Pronoun A remains bare in matched perception and transfer rows.", "Rule 129: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about rows retain ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 129: ask-about syntax."),
    ("syntax", "`yajarri-l` laugh rows retain sourced DAT:pt targets and no ERG marking on the laugher.", "Rule 129: laugh target syntax."),
    ("fidelity", "English plurals such as leaves/seeds are not treated as a license to invent number morphology.", "Rule 129: number restraint."),
    ("fidelity", "Transferred rows preserve old case frames; the new content noun is the object, not a source for new grammar.", "Rule 129: object-frame fidelity."),
    ("register", "The batch stays plain and practical: leaves, bark, smoke, stones, sand, seeds, flowers, fog, mountain, scrub, seeing, moving, asking, laughing, and companion motion.", "Rule 129: register scope."),
]

LEXEMES = [
    ("birra", "noun", None, "NA", "leaf", "batch-171: leaf sense selected; lungs sense explicitly excluded."),
    ("dumbul", "noun", None, "NA", "bark; hard covering", "batch-171: bark sense used in rest, placement, leaving, and perception rows."),
    ("kubu", "noun", None, "NA", "smoke", "batch-171: smoke as coming/perceived object."),
    ("kulji", "noun", None, "NA", "stone; rock; pebbles", "batch-171: stone/rock sense used; not mountain; no kulji-bu instrument."),
    ("jukar", "noun", None, "NA", "sand", "batch-171: sand as rest, placed, transferred, and perceived object."),
    ("manjal", "noun", None, "NA", "mountain", "batch-171: mountain place/object; contrast with kulji."),
    ("madja", "noun", None, "NA", "scrub; rainforest", "batch-171: scrub/rainforest place in motion and comitative rows."),
    ("diburr", "noun", None, "NA", "seed; egg", "batch-171: seed sense selected; egg/bullet/tablet extensions excluded."),
    ("nganka", "noun", None, "NA", "flower; blossom", "batch-171: flower as tree-located, placed, and perceived object."),
    ("ngurrbal", "noun", None, "NA", "fog", "batch-171: fog as rest/perceived object."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-171: retained ground LOC with bark/seeds/perception."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-171: retained shade LOC with leaves/stone."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-171: retained bag LOC with sand/flower/seeds."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-171: retained road LOC with stone."),
    ("bayan-ka", "case-form", None, "DAT", "to camp/house", "batch-171: retained transfer goal."),
    ("bayan-muny", "case-form", None, "ABL", "from camp/house", "batch-171: retained source form."),
    ("juku-ngu", "case-form", None, "LOC", "in/on the tree", "batch-171: retained tree LOC with flower/leaves/clothes comitative."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-171: retained outside LOC with fog/smoke/bark."),
    ("manjal-ba", "case-form", None, "LOC", "on/to the mountain", "batch-171: retained mountain LOC."),
    ("madja-nga", "case-form", None, "LOC", "in/to the scrub", "batch-171: retained scrub LOC."),
    ("bana-ka", "case-form", None, "DAT", "about water", "batch-171: retained ask-about topic."),
    ("bana-nga", "case-form", None, "LOC", "in the water", "batch-171: retained water LOC in comitative motion row."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-171: retained ask-about topic."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-171: retained ask-about topic."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-171: retained loan/contact ask-about topic."),
    ("ngamu-ndu", "case-form", None, "LOC:pt/DAT:pt", "at/to mother", "batch-171: ask/laugh person form."),
    ("nganjan-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to father", "batch-171: ask/laugh person form."),
    ("babi-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandmother", "batch-171: ask/laugh person form."),
    ("kami-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandfather", "batch-171: ask/laugh person form."),
    ("maral-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to the girl", "batch-171: laugh person form."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-171: closed comitative."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-171: closed comitative."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-171: closed comitative."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-171: closed sourced comitative only, not an instrument analogy."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-171: closed sourced comitative."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-171: rest rows."),
    ("kada-y", "verb", "y", "NA", "come", "batch-171: smoke source row."),
    ("jana-y", "verb", "y", "NA", "stand; be", "batch-171: flower-on-tree row."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-171: motion and comitative motion rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-171: placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-171: leave-location rows."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-171: transfer rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-171: perception rows."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-171: ask-about rows."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-171: laugh-target rows."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-171: old man staying 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-171-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After banking, lint scanned 8,647 rows and found 0 issues; verified total remained 8,597 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8647 rows scanned, 0 issues flagged; GOAL METRIC: 8597 / 20000 verified sentences (93929 Kuku words)",
        artifact_path=PROCESS_LOG,
        created_at=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 129 rows. Morphology checked retained LOC, ABL, DAT, "
            "LOC:pt/DAT:pt, COMIT, ERG, past, and nonpast forms with no new instruments or comitatives. Lexicon "
            "checked birra leaf, dumbul bark, kubu smoke, kulji stone/rock not mountain, jukar sand, manjal mountain, "
            "madja scrub, diburr seed, nganka flower, and ngurrbal fog. Syntax checked rest, coming, standing, "
            "placement, leaving, transfer, perception, ask-about, laugh-target, and closed-comitative rows. Fidelity "
            "checked sense exclusions and duplicate freedom. Register stayed plain."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="review-detail",
        actor="claude-main",
        detail=(
            "Final review retained these decisions: exclude warrur for this pass; no generator-authored rows; birra not "
            "lungs; dumbul bark only; diburr seed only; kulji not mountain; no kulji-bu; wulman/mayngku loan-contact "
            "forms logged; common-noun nyaji-l perceivers ERG-marked; pronoun A bare; babaji-y askers not ERG-marked; "
            "yajarri-l targets DAT:pt; comitatives limited to the closed sourced set."
        ),
        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 129 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_171.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 129 heads, case forms, comitatives, and predicates.",
        artifact_path="batch_scripts/close_171.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 171: 50 accepted Rule 129 lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_171.py",
        artifact_path="batch_scripts/close_171.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-171-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())
