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

from __future__ import annotations

import datetime as dt
import json
import sqlite3

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-184"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-184-construction-consolidation-after-rule141-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 141 (Rule 142). 50 rows. TARGETS RETAINED: babajaka bloodwood tree, "
    "bajar Moreton Bay ash/white gum tree, baril-baril Moreton Bay fig tree, baway black bean tree, bilar candlenut "
    "tree, kabal Leichhardt tree, mili stinging tree, yalngkal white wattle, yumu bottlebrush tree. FRAMES: state, "
    "standing, perception. REVIEW: no new target heads; no bajar residue ash; no mili jellyfish/burn/instrument; no "
    "target case forms; no instruments, comitatives, possessives, compounds, fruit/nut/bark/medicine/spear/canoe/"
    "basket/use rows; common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "A construction pass after a named-tree lexical batch should recombine the same tree heads rather than opening tree-use ecology.", "Rule 142: construction cadence."),
    ("process", "Duplicate preflight caught `Yalngkal yinyay janjanay.` as an older accepted row and the row was replaced before banking.", "Rule 142: duplicate preflight repair."),
    ("process", "The no-use-scene guard must allow lexical names such as candlenut tree while still banning nut-use scenes.", "Rule 142: guard precision."),
    ("lexicon", "`babajaka` stayed bloodwood tree only.", "Rule 142: babajaka."),
    ("lexicon", "`bajar` stayed Moreton Bay ash / white gum tree only; residue ash remained forbidden.", "Rule 142: bajar."),
    ("lexicon", "`baril-baril` stayed a whole Moreton Bay fig tree lexical head.", "Rule 142: baril-baril."),
    ("lexicon", "`baway` stayed black bean tree only; edible-fruit rows stayed closed.", "Rule 142: baway."),
    ("lexicon", "`bilar` stayed candlenut tree only; nut-use rows stayed closed.", "Rule 142: bilar."),
    ("lexicon", "`kabal` stayed Leichhardt tree only; fruit and bark-medicine rows stayed closed.", "Rule 142: kabal."),
    ("lexicon", "`mili` stayed stinging tree only; jellyfish, burn, and instrument readings stayed closed.", "Rule 142: mili."),
    ("lexicon", "`yalngkal` stayed white wattle only.", "Rule 142: yalngkal."),
    ("lexicon", "`yumu` stayed bottlebrush tree only.", "Rule 142: yumu."),
    ("morphology", "All tree target heads stayed bare; no target dative, locative, ablative, instrumental, comitative, possessive, or compound forms appeared.", "Rule 142: target case restraint."),
    ("morphology", "`Baril-baril` remained lexical and whole, not split or productively reduplicated.", "Rule 142: lexical reduplication."),
    ("morphology", "The only support local forms were `bayan-ba`, `madja-nga`, and `ngalkal-ba`; `yinyay` stayed deictic support.", "Rule 142: support form limit."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 142: A marking."),
    ("syntax", "State rows stayed simple noun-predicate clauses with `ngulkurr`, `yalbay`, or `marral`.", "Rule 142: state syntax."),
    ("syntax", "Standing rows used `janjanay` with one support location or deictic where needed.", "Rule 142: standing syntax."),
    ("syntax", "Perception rows used `nyajin` with bare tree objects and optional support location.", "Rule 142: perception syntax."),
    ("fidelity", "English labels explicitly preserve tree senses, especially Moreton Bay ash tree and stinging tree.", "Rule 142: selected-sense fidelity."),
    ("fidelity", "No row translated `bajar` as ash residue or `mili` as jellyfish/burn instrument.", "Rule 142: polysemy control."),
    ("fidelity", "No fruit, nut, edible, bark-use, medicine, spear, canoe, basket, or material-use inference was imported.", "Rule 142: no use inference."),
    ("register", "Rows remained ordinary descriptions of trees being good/big/dry, standing somewhere, or being seen.", "Rule 142: register scope."),
    ("handoff", "Next cadence may return to lexical expansion only after a fresh source pass; keep all named-tree traps active.", "Rule 142: next cadence."),
    ("handoff", "Future tree-use rows need their own lexical/source pass and should not be inferred from tree-name rows.", "Rule 142: future tree-use warning."),
]

LEXEMES = [
    ("babajaka", "noun", None, "NA", "bloodwood tree", "batch-184: retained bloodwood tree only."),
    ("bajar", "noun", None, "NA", "Moreton Bay ash; white gum tree", "batch-184: retained tree sense only; residue ash remains forbidden."),
    ("baril-baril", "noun", None, "NA", "Moreton Bay fig tree", "batch-184: retained whole reduplicated tree head."),
    ("baway", "noun", None, "NA", "black bean tree", "batch-184: retained tree sense only; edible fruit not opened."),
    ("bilar", "noun", None, "NA", "candlenut tree", "batch-184: retained tree sense only; nut use not opened."),
    ("kabal", "noun", None, "NA", "Leichhardt tree", "batch-184: retained tree sense only; fruit/bark uses not opened."),
    ("mili", "noun", None, "NA", "stinging tree", "batch-184: retained stinging tree only; jellyfish/burn/instrument not opened."),
    ("yalngkal", "noun", None, "NA", "white wattle", "batch-184: retained white wattle tree only."),
    ("yumu", "noun", None, "NA", "bottlebrush tree", "batch-184: retained bottlebrush tree only."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-184: support-only location in bayan-ba camp LOC."),
    ("madja", "noun", None, "NA", "scrub", "batch-184: support-only location in madja-nga scrub LOC."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-184: support-only outside location in ngalkal-ba."),
    ("yinyay", "locational", None, "NA", "there", "batch-184: deictic support in perception row."),
    ("marral", "adjective", None, "NA", "dry", "batch-184: state predicate for named-tree rows."),
    ("yalbay", "adjective", None, "NA", "big", "batch-184: state predicate for named-tree rows."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-184: state predicate for named-tree rows."),
    ("janjana-y", "intransitive-verb", "y", "NA", "stand; be standing", "batch-184: standing rows with named trees."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-184: perception rows with tree objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-184: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-184: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-184: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-184: bare pronoun A in perception 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}")

    total_rows = db.execute("SELECT COUNT(*) FROM sentences WHERE status!='rejected'").fetchone()[0]
    verified_before, words_before = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()

    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
              gloss=excluded.gloss,
              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-184-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail=f"After banking, lint scanned {total_rows} rows and found 0 issues; verified total remained {verified_before} before close.",
        command="python3 lint_corpus.py",
        output_excerpt=f"lint: {total_rows} rows scanned, 0 issues flagged; GOAL METRIC: {verified_before} / 20000 verified sentences ({words_before or 0} 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 142 rows. Morphology checked bare tree targets, no target "
            "case morphology, no instruments/comitatives/possessives, support-only local forms, common-noun A ERG, "
            "and pronoun A bare. Lexicon checked retained tree senses, especially bajar tree not residue ash and "
            "mili stinging tree not jellyfish/burn. Syntax checked state, standing, and perception frames. Fidelity "
            "checked tree-sense English. Register stayed ordinary."
        ),
        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 no residue-ash row, no cooking-ash row, no jellyfish row, no burn row, no target "
            "instrument row, no fruit/nut/bark/medicine/spear/canoe/basket/use row, no target case form, and no "
            "out-of-scope Rule 139/140 material/fire heads."
        ),
        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 142 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_184.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 142 targets, support/deictic heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_184.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 184: 50 accepted Rule 142 named-tree construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_184.py",
        artifact_path="batch_scripts/close_184.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 detail LIKE '%batch-184:%'").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, {lesson_count} lessons, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_review_remaining}, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
