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

NOTES = (
    "LEXICAL EXPANSION AFTER RULE 140 (Rule 141). 50 rows. TARGETS: 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, tree standing, "
    "and perception. REVIEW: bajar allowed only as tree name, not residue ash; mili allowed only as stinging tree, "
    "not jellyfish/burn/instrument; no target case forms, no instruments, no comitatives, no possessives, no compounds, "
    "no fruit/nut/bark/medicine/spear/canoe/basket/use rows; common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "A lexical batch can reopen a previously dangerous string only by selecting the exact sourced sense and naming the trap in every risk-control layer.", "Rule 141: bajar tree-sense discipline."),
    ("process", "Named-tree rows should stay as tree names before any use/material/fruit ecology is opened.", "Rule 141: tree-name-first sequence."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 141: duplicate preflight."),
    ("lexicon", "`babajaka` selected bloodwood tree only.", "Rule 141: babajaka."),
    ("lexicon", "`bajar` selected Moreton Bay ash / white gum tree only; residue ash remains forbidden.", "Rule 141: bajar."),
    ("lexicon", "`baril-baril` selected Moreton Bay fig tree and remained a whole reduplicated lexical head.", "Rule 141: baril-baril."),
    ("lexicon", "`baway` selected black bean tree only; edible-fruit rows were not opened.", "Rule 141: baway."),
    ("lexicon", "`bilar` selected candlenut tree only; nut eating/roasting rows were not opened.", "Rule 141: bilar."),
    ("lexicon", "`kabal` selected Leichhardt tree only; fruit and bark-medicine uses stayed closed.", "Rule 141: kabal."),
    ("lexicon", "`mili` selected stinging tree only; jellyfish extension and burn frames stayed closed.", "Rule 141: mili."),
    ("lexicon", "`yalngkal` selected white wattle only.", "Rule 141: yalngkal."),
    ("lexicon", "`yumu` selected bottlebrush tree only.", "Rule 141: yumu."),
    ("morphology", "All tree target heads stayed bare; no dative, locative, ablative, instrumental, comitative, possessive, or compound target form appeared.", "Rule 141: target case restraint."),
    ("morphology", "`baril-baril` was treated as an internal reduplicated lexical head, not as productive reduplication or a detachable compound.", "Rule 141: lexical reduplication."),
    ("morphology", "The only support local forms in the batch were already verified `madja-nga` scrub LOC and `ngalkal-ba` outside LOC.", "Rule 141: support form limit."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 141: A marking."),
    ("syntax", "State rows stayed simple noun-predicate clauses using `yalbay` and `ngulkurr`.", "Rule 141: state syntax."),
    ("syntax", "Standing rows used the Patz-modeled tree-standing frame with `janjanay` and optional deictic/location support.", "Rule 141: standing syntax."),
    ("syntax", "Perception rows used `nyajin` with bare tree objects and optional support location.", "Rule 141: perception syntax."),
    ("fidelity", "English labels explicitly name the selected tree senses, especially Moreton Bay ash tree and stinging tree.", "Rule 141: selected-sense fidelity."),
    ("fidelity", "No row translated `bajar` as ash residue or `mili` as jellyfish.", "Rule 141: polysemy control."),
    ("fidelity", "No fruit, nut, edible, bark-use, medicine, spear, canoe, basket, or material-use inference was imported from dictionary comments.", "Rule 141: no use inference."),
    ("register", "Rows remain ordinary observation and description sentences about known trees being good/big, standing somewhere, or being seen.", "Rule 141: register scope."),
    ("handoff", "The next batch should normally consolidate these named-tree heads before opening tree uses or fruit/nut scenes.", "Rule 141: next cadence."),
    ("handoff", "Keep `bajar` residue-ash and `mili` jellyfish/burn traps active in future batches.", "Rule 141: carry-forward traps."),
]

LEXEMES = [
    ("babajaka", "noun", None, "NA", "bloodwood tree", "batch-183: selected bloodwood tree only."),
    ("bajar", "noun", None, "NA", "Moreton Bay ash; white gum tree", "batch-183: selected tree sense only; residue ash remains forbidden."),
    ("baril-baril", "noun", None, "NA", "Moreton Bay fig tree", "batch-183: selected whole reduplicated tree head."),
    ("baway", "noun", None, "NA", "black bean tree", "batch-183: selected tree sense only; edible fruit not opened."),
    ("bilar", "noun", None, "NA", "candlenut tree", "batch-183: selected tree sense only; nut use not opened."),
    ("kabal", "noun", None, "NA", "Leichhardt tree", "batch-183: selected tree sense only; fruit/bark uses not opened."),
    ("mili", "noun", None, "NA", "stinging tree", "batch-183: selected stinging tree only; jellyfish and burn frames not opened."),
    ("yalngkal", "noun", None, "NA", "white wattle", "batch-183: selected white wattle tree only."),
    ("yumu", "noun", None, "NA", "bottlebrush tree", "batch-183: selected bottlebrush tree only."),
    ("madja", "noun", None, "NA", "scrub", "batch-183: support-only location in madja-nga scrub LOC."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-183: support-only outside location in ngalkal-ba."),
    ("yinyay", "locational", None, "NA", "there", "batch-183: deictic support in standing/perception rows."),
    ("yalbay", "adjective", None, "NA", "big", "batch-183: state predicate for named-tree rows."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-183: state predicate for named-tree rows."),
    ("janjana-y", "intransitive-verb", "y", "NA", "stand; be standing", "batch-183: standing rows with named trees."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-183: perception rows with tree objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-183: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-183: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-183: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-183: 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-183-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 141 rows. Morphology checked bare tree heads, baril-baril "
            "as whole lexical reduplication, no target case morphology, no instruments/comitatives/possessives, "
            "common-noun A ERG, and pronoun A bare. Lexicon checked selected tree senses, especially bajar tree "
            "not residue ash and mili stinging tree not jellyfish. Syntax checked state, standing, and perception "
            "frames. Fidelity checked English labels. 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 141 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_183.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 141 targets, support/deictic heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_183.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 183: 50 accepted Rule 141 named-tree lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_183.py",
        artifact_path="batch_scripts/close_183.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-183:%'").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())
