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

NOTES = (
    "CONSTRUCTION: CONSOLIDATION AFTER RULE 129 (Rule 130). 50 rows. DESIGN: hand-authored consolidation of "
    "Rule 129 material/landscape heads in retained rest, coming/source, standing, placement, leaving, transfer, "
    "perception, ask-about, laugh-target, and closed-comitative frames. SOURCE CONTROLS: exact dictionary, Patz "
    "grammar, and lexeme-table readback; no new lexical heads; no generator-authored rows; no new instrument, "
    "comitative, possessive, or abstract case analogy. REVIEW: birra leaf not lungs, dumbul bark only, diburr seed "
    "only, kulji stone/rock not mountain, manjal mountain, warrur excluded, 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 construction batch after a lexical pass should use the new heads in old frames, not add another vocabulary field.", "Rule 130: construction cadence."),
    ("process", "Duplicate scanning remains high-risk around ask/laugh rows; Batch 172 scanned all 50 planned surfaces before banking.", "Rule 130: duplicate scan."),
    ("process", "Source readback can reuse the previous lexical pass, but only after checking the current dictionary, grammar, and lexeme table again.", "Rule 130: source readback."),
    ("lexicon", "`birra` remains leaf only in this consolidation; the lungs sense is still excluded.", "Rule 130: birra."),
    ("lexicon", "`dumbul` remains bark only here, despite broader hard-covering senses.", "Rule 130: dumbul."),
    ("lexicon", "`diburr` remains seed only here; egg/bullet/tablet extensions are not imported.", "Rule 130: diburr."),
    ("lexicon", "`kulji` remains stone/rock/pebbles, never mountain; `manjal` remains mountain.", "Rule 130: kulji/manjal."),
    ("lexicon", "`kubu`, `jukar`, `madja`, `nganka`, and `ngurrbal` remain smoke, sand, scrub, flower, and fog.", "Rule 130: other heads."),
    ("morphology", "No `kulji-bu` or other instrument row was admitted in the consolidation pass.", "Rule 130: no instruments."),
    ("morphology", "`bubu-ngu`, `juku-ngu`, `madja-nga`, `manjal-ba`, `ngalkal-ba`, `wabarr-ba`, `balji-nga`, and `baral-ba` remain LOC forms.", "Rule 130: locatives."),
    ("morphology", "`bayan-ka`, `bayan-muny`, and `madja-muny` remain controlled goal/source forms.", "Rule 130: transfer cases."),
    ("morphology", "The only comitatives used were closed sourced forms: `ngawa-nji` and `juku-ji`.", "Rule 130: closed comitatives."),
    ("syntax", "Matched common-noun/pronoun perception rows keep common-noun A ERG and pronoun A bare.", "Rule 130: perception contrast."),
    ("syntax", "`babaji-y` rows keep ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 130: ask-about frame."),
    ("syntax", "`yajarri-l` rows keep ABS/S laugher and DAT:pt target.", "Rule 130: laugh-target frame."),
    ("syntax", "Transfer rows keep the moved object overt before the source or goal case phrase.", "Rule 130: transfer object visibility."),
    ("fidelity", "English plurals in leaves/seeds do not create number morphology; the Kuku surfaces remain simple noun heads.", "Rule 130: number restraint."),
    ("fidelity", "`warrur` remains deferred; construction consolidation did not sneak it back in.", "Rule 130: deferred head."),
    ("register", "The batch stays plain and practical: materials, places, seeing, moving, asking, laughing, and companion motion.", "Rule 130: register scope."),
    ("process", "Process evidence now records source readback, exact duplicate scan, bank, lint, five-lens close, export, docs, and live checks.", "Rule 130: process capture."),
]

LEXEMES = [
    ("birra", "noun", None, "NA", "leaf", "batch-172: leaf sense consolidated; lungs sense excluded."),
    ("dumbul", "noun", None, "NA", "bark; hard covering", "batch-172: bark sense consolidated."),
    ("kubu", "noun", None, "NA", "smoke", "batch-172: smoke as source/perceived object."),
    ("kulji", "noun", None, "NA", "stone; rock; pebbles", "batch-172: stone/rock sense consolidated; not mountain; no kulji-bu."),
    ("jukar", "noun", None, "NA", "sand", "batch-172: sand in rest, transfer, and perception frames."),
    ("manjal", "noun", None, "NA", "mountain", "batch-172: mountain place/object; contrast with kulji."),
    ("madja", "noun", None, "NA", "scrub; rainforest", "batch-172: scrub place/source/object frames."),
    ("diburr", "noun", None, "NA", "seed; egg", "batch-172: seed sense consolidated; egg/bullet/tablet extensions excluded."),
    ("nganka", "noun", None, "NA", "flower; blossom", "batch-172: flower rest/leave/perception rows."),
    ("ngurrbal", "noun", None, "NA", "fog", "batch-172: fog rest/perception rows."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-172: retained ground LOC."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-172: retained shade LOC."),
    ("madja-muny", "case-form", None, "ABL", "from the scrub", "batch-172: retained scrub source."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-172: retained bag LOC."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-172: retained outside LOC."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-172: retained camp LOC."),
    ("manjal-ba", "case-form", None, "LOC", "on/to the mountain", "batch-172: retained mountain LOC."),
    ("madja-nga", "case-form", None, "LOC", "in/to the scrub", "batch-172: retained scrub LOC."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-172: retained source form."),
    ("bayan-ka", "case-form", None, "DAT", "to camp/house", "batch-172: retained transfer goal."),
    ("juku-ngu", "case-form", None, "LOC", "in/on the tree", "batch-172: retained tree LOC."),
    ("ngamu-ndu", "case-form", None, "LOC:pt/DAT:pt", "at/to mother", "batch-172: ask/laugh person form."),
    ("kami-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandfather", "batch-172: ask/laugh person form."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-172: retained ask-about topic."),
    ("babi-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandmother", "batch-172: ask/laugh person form."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-172: retained ask-about topic."),
    ("maral-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to the girl", "batch-172: ask/laugh person form."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-172: retained loan/contact ask-about topic."),
    ("bana-ka", "case-form", None, "DAT", "about water", "batch-172: retained ask-about topic."),
    ("nganjan-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to father", "batch-172: ask/laugh person form."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-172: closed comitative."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-172: closed sourced comitative only."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-172: rest rows."),
    ("kada-y", "verb", "y", "NA", "come", "batch-172: smoke source row."),
    ("jana-y", "verb", "y", "NA", "stand; be", "batch-172: stand/be rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-172: placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-172: leave-location rows."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-172: transfer rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-172: perception rows."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-172: ask-about rows."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-172: laugh-target rows."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-172: closed-comitative motion 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-172-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,697 rows and found 0 issues; verified total remained 8,647 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8697 rows scanned, 0 issues flagged; GOAL METRIC: 8647 / 20000 verified sentences (94112 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 130 rows. Morphology checked retained LOC, ABL, DAT, "
            "LOC:pt/DAT:pt, COMIT, ERG, past, and nonpast forms with no new instruments. Lexicon checked all Rule 129 "
            "heads and sense exclusions. Syntax checked rest, coming, standing, placement, leaving, transfer, perception, "
            "ask-about, laugh-target, and closed-comitative rows. Fidelity checked no new heads, no warrur, no kulji-bu, "
            "duplicate freedom, and honest LOC/source glossing. 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: no new lexical heads; birra leaf not lungs; dumbul bark only; diburr "
            "seed only; kulji not mountain; no kulji-bu; warrur excluded; mayngku and wulman 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 closed sourced forms."
        ),
        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 130 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_172.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 130 heads, case forms, comitatives, and predicates.",
        artifact_path="batch_scripts/close_172.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 172: 50 accepted Rule 130 construction rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_172.py",
        artifact_path="batch_scripts/close_172.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-172-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())
