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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 139 (Rule 140). 50 rows. TARGETS RETAINED: jimal fire stick, "
    "ngunjil charcoal/hot coals, dumbul bark, buyku paperbark, jikan grass, baya fire/firewood, kubu smoke, "
    "nganjirr grass tree. SUPPORT: balji-nga bag LOC, bubu-ngu ground LOC, bubu-muny ground ABL, wabarr-ba "
    "shade LOC, bayan-ba camp/house LOC, ngalkal-ba outside LOC. DESIGN: no new target heads; recombined Rule "
    "139 heads in state, rest-location, perception, placement, leave, and get/source frames. REVIEW: no bajar "
    "residue-ash rows, no ngalku grassfire, no Rule 137/138 carry-over targets, no target case forms, no "
    "instruments, no comitatives, no possessives, no temporal clitics, no unsourced analogies. Baya fire only "
    "in state/perception here; kubu smoke only; nganjirr grass tree only; dumbul bark only; common-noun A ERG, "
    "pronoun A bare."
)

LESSONS = [
    ("process", "A construction pass after Rule 139 should recombine the same camp/fire-material heads rather than opening another lexical field.", "Rule 140: construction cadence."),
    ("process", "Rule 140 added `ngalkal-ba` only after dictionary, grammar, and lexeme readback confirmed outside LOC.", "Rule 140: support expansion discipline."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 140: duplicate preflight."),
    ("lexicon", "`jimal` stayed fire stick only; no fire-making compound or instrument form entered.", "Rule 140: jimal."),
    ("lexicon", "`ngunjil` stayed charcoal/hot coals; no English ash wording and no `bajar` head entered.", "Rule 140: ngunjil."),
    ("lexicon", "`dumbul` stayed bark only; shell and crust senses remained excluded.", "Rule 140: dumbul."),
    ("lexicon", "`buyku` stayed paperbark, with Text 51 paperbark context retained as source support.", "Rule 140: buyku."),
    ("lexicon", "`jikan` stayed grass; no target locative or perlative form entered.", "Rule 140: jikan."),
    ("lexicon", "`baya` stayed fire in Rule 140 state/perception rows; no firewood handled-object row was opened.", "Rule 140: baya."),
    ("lexicon", "`kubu` stayed smoke only and appeared only in perception rows.", "Rule 140: kubu."),
    ("lexicon", "`nganjirr` stayed grass tree only and appeared only in state/perception rows.", "Rule 140: nganjirr."),
    ("lexicon", "`bajar` remains a rejected residue-ash candidate; it is Moreton Bay ash/white gum tree.", "Rule 140: bajar trap."),
    ("lexicon", "`ngalkal` was admitted support-only as outside/open-ground location, chiefly `ngalkal-ba`.", "Rule 140: ngalkal support."),
    ("morphology", "All target heads stayed bare; no dative, locative, ablative, instrumental, comitative, possessive, or compound target form appeared.", "Rule 140: target case restraint."),
    ("morphology", "The only support local forms admitted were `balji-nga`, `bubu-ngu`, `bubu-muny`, `wabarr-ba`, `bayan-ba`, and `ngalkal-ba`.", "Rule 140: support case whitelist."),
    ("morphology", "Common-noun A in perception, placement, leaving, and getting rows was ERG-marked; pronoun A rows stayed bare.", "Rule 140: A marking."),
    ("syntax", "State rows stayed simple noun-predicate clauses with already verified predicates.", "Rule 140: state syntax."),
    ("syntax", "Rest rows were reserved for portable material nouns and used one sourced local support phrase plus `wunan`.", "Rule 140: rest syntax."),
    ("syntax", "Perception rows admitted fire, smoke, and grass tree without converting them into handled-object themes.", "Rule 140: perception syntax."),
    ("syntax", "Placement, leave, and get/source rows were reserved for fire stick, charcoal, bark, paperbark, and grass.", "Rule 140: handled-material syntax."),
    ("fidelity", "English labels narrow the selected senses: fire stick, charcoal, bark, paperbark, grass, fire, smoke, and grass tree.", "Rule 140: selected-sense fidelity."),
    ("fidelity", "Rows with `ngunjil` are English charcoal rows, never ash rows.", "Rule 140: charcoal fidelity."),
    ("fidelity", "`ngalkal-ba` rows mean outside, not a new target or an unglossed location.", "Rule 140: support fidelity."),
    ("register", "The batch stays ordinary and practical: materials are good/big/dry, lying somewhere, seen, put, left, or taken.", "Rule 140: register scope."),
    ("handoff", "Next cadence may return to lexical expansion only after a fresh source pass; keep the bajar/ngalku and nonportable-target traps active.", "Rule 140: next cadence."),
]

LEXEMES = [
    ("jimal", "noun", None, "NA", "fire stick", "batch-182: construction consolidation retained fire-stick noun only."),
    ("ngunjil", "noun", None, "NA", "charcoal; hot coals", "batch-182: retained charcoal/hot-coals noun; no residue-ash wording."),
    ("dumbul", "noun", None, "NA", "bark; hard covering", "batch-182: retained bark sense only; shell/crust excluded."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-182: retained paperbark noun."),
    ("jikan", "noun", None, "NA", "grass", "batch-182: retained grass noun; no target local case forms."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-182: retained fire sense in state/perception; no handled firewood rows."),
    ("kubu", "noun", None, "NA", "smoke", "batch-182: smoke noun only, restricted to perception rows."),
    ("nganjirr", "noun", None, "NA", "grass tree", "batch-182: grass-tree noun only; state/perception rows only."),
    ("bajar", "noun", None, "NA", "Moreton Bay ash; white gum tree", "batch-182: still rejected as residue-ash source; dictionary defines a tree, not ash residue."),
    ("ngalku", "noun", None, "NA", "bush fire; grassfire", "batch-182: source-known but deliberately unopened."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-182: support-only outside location, especially ngalkal-ba."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-182: support-only container noun in balji-nga bag LOC."),
    ("bubu", "noun", None, "NA", "ground; place; country", "batch-182: support local forms bubu-ngu ground LOC and bubu-muny ground ABL."),
    ("wabarr", "noun", None, "NA", "shade", "batch-182: support locative wabarr-ba shade LOC."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-182: support locative bayan-ba camp/house LOC."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-182: state predicate for charcoal, bark, paperbark, and fire."),
    ("marral", "adjective", None, "NA", "dry", "batch-182: state predicate for grass tree."),
    ("yalbay", "adjective", None, "NA", "big", "batch-182: state predicate for grass, fire stick, and fire."),
    ("wuna-y", "intransitive-verb", "y", "NA", "lie down", "batch-182: rest/location rows with past wunan for portable materials."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-182: perception rows with common-noun A ERG and pronoun A bare."),
    ("yijarri-l", "verb", "l", "NA", "put; place", "batch-182: placement rows with portable material objects plus local complement."),
    ("bawa-l", "verb", "l", "NA", "leave; leave alone", "batch-182: leave rows with portable material objects plus local complement."),
    ("mani-l", "transitive-verb", "l", "NA", "get; take", "batch-182: get/take rows with bubu-muny source."),
    ("ngamu", "noun", None, "NA", "mother", "batch-182: common-noun A in object rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-182: common-noun A in object rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-182: common-noun A in object rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-182: common-noun A in object rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-182: common-noun A in object rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-182: common-noun A in object rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-182: common-noun A in object rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-182: bare pronoun A in object rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-182: bare pronoun A in perception/get rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-182: bare pronoun A in perception 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}")

    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
              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-182-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 140 rows. Morphology checked bare targets, allowed support "
            "local forms only, no instruments/comitatives/possessives/temporal clitics, common-noun A ERG, and "
            "pronoun A bare. Lexicon checked Rule 139 selected senses, ngalkal support-only outside LOC, bajar "
            "rejection, and unopened ngalku. Syntax checked state, rest-location, perception, placement, leave, "
            "and get/source frames with nonportable limits for baya/kubu/nganjirr. Fidelity checked selected-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 bajar residue-ash row, no ngalku grassfire row, no target case forms, no "
            "instruments, no comitatives, no possessive suffixes, no temporal clitics, no Rule 137/138 carry-over "
            "targets, no dumbul shell/crust sense, no nonportable-object treatment of baya/kubu/nganjirr, and no "
            "unapproved local 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 140 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_182.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 140 targets, rejected/unopened traps, support heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_182.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 182: 50 accepted Rule 140 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_182.py",
        artifact_path="batch_scripts/close_182.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-182-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__":
    raise SystemExit(main())
