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

NOTES = (
    "CAMP/FIRE-MATERIAL LEXICAL EXPANSION AFTER RULE 138 (Rule 139). 50 rows. TARGETS: jimal fire stick, "
    "ngunjil charcoal/hot coals, dumbul bark, buyku paperbark, jikan grass, baya fire/firewood, kubu smoke, "
    "nganjirr grass tree. REJECTED TRAP: bajar is Moreton Bay ash/white gum tree, not residue ash; no bajar "
    "residue row admitted. SUPPORT: balji-nga bag LOC, bubu-ngu ground LOC, bubu-muny ground ABL, wabarr-ba "
    "shade LOC, bayan-ba camp/house LOC. REVIEW: no ngalku grassfire, no Rule 137/138 handled-object carry-over "
    "heads, no target case forms, no instruments, no comitatives, no possessives, no temporal clitics, no "
    "unsourced analogies. Baya is fire/firewood only; kubu smoke only; nganjirr grass tree only; dumbul bark "
    "only in this batch. Common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "Rule 139 returned to lexical expansion only after a fresh source pass, rather than extending Rule 137/138 object frames by habit.", "Rule 139: lexical-expansion cadence."),
    ("process", "Exact duplicate preflight caught `Jikan marral` and `Dingkar-angka kubu nyajin`; both were replaced before banking.", "Rule 139: duplicate repair."),
    ("process", "A source gloss that looks English-obvious can still be a trap: dictionary `bajar` is a tree name, not residue ash.", "Rule 139: ash-trap discipline."),
    ("process", "`Ngalku` was source-available as bush fire/grassfire but left out to keep this field focused on materials plus fire/smoke perception.", "Rule 139: scope restraint."),
    ("lexicon", "`jimal` was selected only as fire stick; no fire-making compound or instrument form entered the rows.", "Rule 139: jimal."),
    ("lexicon", "`ngunjil` was selected as charcoal/hot coals; English and analysis avoid residue-ash wording.", "Rule 139: ngunjil."),
    ("lexicon", "`dumbul` was selected as bark; shell and crust senses were excluded.", "Rule 139: dumbul."),
    ("lexicon", "`buyku` was selected as paperbark, supported by dictionary and Text 51 earth-oven paperbark context.", "Rule 139: buyku."),
    ("lexicon", "`jikan` was selected as grass; target case forms such as jikan-ba were deliberately excluded.", "Rule 139: jikan."),
    ("lexicon", "`baya` was selected as fire/firewood only; dry-state row explicitly means firewood, perception rows mean fire.", "Rule 139: baya."),
    ("lexicon", "`kubu` was selected as smoke only and stayed in state/perception rows.", "Rule 139: kubu."),
    ("lexicon", "`nganjirr` was selected as grass tree and restricted to state/perception so it was not treated as a portable object.", "Rule 139: nganjirr."),
    ("lexicon", "`bajar` was logged as a rejected residue-ash candidate because Patz dictionary definitions specify Moreton Bay ash/white gum tree.", "Rule 139: bajar trap."),
    ("morphology", "All target heads stayed bare; no dative, locative, ablative, instrumental, comitative, possessive, or compound target form appeared.", "Rule 139: target case restraint."),
    ("morphology", "The only local-case support forms admitted were `balji-nga`, `bubu-ngu`, `wabarr-ba`, `bayan-ba`, and `bubu-muny`.", "Rule 139: support case whitelist."),
    ("morphology", "Common-noun A in perception, placement, leaving, and getting rows was ERG-marked; pronoun A rows stayed bare.", "Rule 139: A marking."),
    ("syntax", "State rows used simple noun-predicate clauses with sourced predicates good, dry, and big.", "Rule 139: state syntax."),
    ("syntax", "Rest rows were limited to portable material nouns and used target subject plus one sourced local complement plus `wunan`.", "Rule 139: rest syntax."),
    ("syntax", "Perception rows admitted fire, smoke, and grass tree without forcing them into handled-object frames.", "Rule 139: perception syntax."),
    ("syntax", "Placement, leave, and get/source frames were reserved for fire stick, charcoal, bark, paperbark, and grass.", "Rule 139: handled-material syntax."),
    ("fidelity", "English labels narrow the selected senses: fire stick, charcoal, bark, paperbark, grass, fire/firewood, smoke, and grass tree.", "Rule 139: selected-sense fidelity."),
    ("fidelity", "Rows with `baya` distinguish fire from firewood in English and analysis so the material-state sentence does not imply a flame can be dry.", "Rule 139: baya fidelity."),
    ("fidelity", "Rows with `ngunjil` never use English 'ash', because the available ash-looking head was a tree-name trap.", "Rule 139: charcoal fidelity."),
    ("register", "The batch stays ordinary and practical: materials are good/dry/big, lying somewhere, seen, put, left, or taken.", "Rule 139: register scope."),
    ("handoff", "Next cadence should consolidate Rule 139 heads or open a new field only after another source pass; keep bajar/ngalku and nonportable-target traps active.", "Rule 139: next cadence."),
]

LEXEMES = [
    ("jimal", "noun", None, "NA", "fire stick", "batch-181: selected fire-stick noun only; no fire-making compound or instrument form."),
    ("ngunjil", "noun", None, "NA", "charcoal; hot coals", "batch-181: selected charcoal/hot-coals noun; no residue-ash wording."),
    ("dumbul", "noun", None, "NA", "bark; hard covering", "batch-181: selected bark sense only; shell/crust excluded."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-181: selected paperbark noun; Text 51 paperbark context retained."),
    ("jikan", "noun", None, "NA", "grass", "batch-181: selected grass noun; no target locative/perlative forms."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-181: selected fire/firewood noun; firewood in dry state, fire in perception rows."),
    ("kubu", "noun", None, "NA", "smoke", "batch-181: smoke noun only, restricted to state/perception."),
    ("nganjirr", "noun", None, "NA", "grass tree", "batch-181: grass-tree noun only; state/perception rows only."),
    ("bajar", "noun", None, "NA", "Moreton Bay ash; white gum tree", "batch-181: rejected as residue-ash source; dictionary defines a tree, not ash residue."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-181: support-only container noun in balji-nga bag LOC."),
    ("bubu", "noun", None, "NA", "ground; place; country", "batch-181: support local forms bubu-ngu ground LOC and bubu-muny ground ABL."),
    ("wabarr", "noun", None, "NA", "shade", "batch-181: support locative wabarr-ba shade LOC."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-181: support locative bayan-ba camp/house LOC."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-181: state predicate for fire stick, grass, and grass tree."),
    ("marral", "adjective", None, "NA", "dry", "batch-181: state predicate for fire stick, bark, paperbark, and firewood."),
    ("yalbay", "adjective", None, "NA", "big", "batch-181: state predicate for smoke and grass tree."),
    ("wuna-y", "intransitive-verb", "y", "NA", "lie down", "batch-181: rest/location rows with past wunan for portable materials."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-181: perception rows with common-noun A ERG and pronoun A bare."),
    ("yijarri-l", "verb", "l", "NA", "put; place", "batch-181: placement rows with portable material objects plus local complement."),
    ("bawa-l", "verb", "l", "NA", "leave; leave alone", "batch-181: leave rows with portable material objects plus local complement."),
    ("mani-l", "transitive-verb", "l", "NA", "get; take", "batch-181: get/take rows with bubu-muny source."),
    ("ngamu", "noun", None, "NA", "mother", "batch-181: common-noun A in object rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-181: common-noun A in object rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-181: common-noun A in object rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-181: common-noun A in object rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-181: common-noun A in object rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-181: common-noun A in object rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-181: common-noun A in object rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-181: bare pronoun A in object rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-181: bare pronoun A in perception row."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-181: bare pronoun A in object 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
              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-181-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 139 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 jimal, ngunjil, dumbul, buyku, jikan, baya, kubu, and nganjirr "
            "selected senses, with bajar rejected as residue ash. Syntax checked state, rest-location, perception, "
            "placement, leave, and get/source frames, with fire/smoke/grass-tree nonportable limits. 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 "
            "heads, 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 139 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_181.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 139 targets, the rejected bajar trap, support heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_181.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 181: 50 accepted Rule 139 camp/fire-material lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_181.py",
        artifact_path="batch_scripts/close_181.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-181-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())
