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

NOTES = (
    "LEXICON: FINE-GRAINED PLANT, TREE, FIBRE, SEED, BARK, AND MATERIAL LEXICON (Rule 109). 50 rows. DESIGN: "
    "source-bounded plant/material batch after Rule 108 demonstrative grammar. SOURCE CONTROLS: Patz inanimate "
    "possessor plant-part examples (birra juku-ngu/juku-muny, mayi juku-ngu/juku-muny, dumbul marra-nga), "
    "comitative leaf attribute, Text 51 Leichhardt-fruit and bark/earth-oven lines, zamia roasting examples, "
    "boiling-in-water frame, and dictionary flora/material entries. PROCESS STORAGE: source pass, exclusions, "
    "duplicate preflight, lint outputs, five-lens review, close, export, and live-doc verification are stored in "
    "process_events and the batch process log."
)

LESSONS = [
    ("lexicon", "Juku covers tree and wood of any size down to a splinter; choose tree/wood sense from frame, not from English habit.", "Rule 109: juku tree/wood scope."),
    ("syntax", "Plant parts on a tree use locative host marking: birra juku-ngu, wakumba juku-ngu, dingal juku-ngu.", "Rule 109: plant-part locatives."),
    ("syntax", "Plant material from a tree uses ablative host marking: birra juku-muny and material-source -muny rows; do not blur LOC and ABL.", "Rule 109: plant-material ablatives."),
    ("lexicon", "Birra is leaf/lung; Batch 151 selects leaf only where a plant host, broad-leaf term, or material context makes that sense explicit.", "Rule 109: birra leaf guard."),
    ("lexicon", "Dumbul is a hard covering such as bark/crust/shell. With marra-nga it means shell/hard covering on zamia nut, not generic bark.", "Rule 109: dumbul covering guard."),
    ("lexicon", "Marra is zamia tree/nut and also wing; plant-food rows must include nut/tree context and avoid the wing sense.", "Rule 109: marra sense guard."),
    ("lexicon", "Kabal is Leichhardt tree and fruit; mayi kabal or kabal mayi selects the fruit sense.", "Rule 109: kabal tree/fruit split."),
    ("lexicon", "Diburr is seed/egg/bullet/tablet by semantic extension. In plant rows, English and bubu-ngu planting context select seed.", "Rule 109: diburr seed guard."),
    ("lexicon", "Barka was deliberately excluded because dictionary entries conflict between yellow water snake and Queensland nut; do not teach it as an ordinary plant lexeme without a new source decision.", "Rule 109: barka exclusion."),
    ("lexicon", "Kakan's prose sense is green upper black-palm material used for dilly bags; ignore the misleading mangrove gloss in new craft rows.", "Rule 109: kakan prose-over-gloss."),
    ("lexicon", "Bilanji and mawu are grass materials for dilly bags; use them as material-source nouns with weaving, not generic lawn/ground cover.", "Rule 109: grass material guard."),
    ("lexicon", "Ngunyin can mean dillybag, bark strips, web, or placenta; wukurril weave selects the craft/bark-strip sense.", "Rule 109: ngunyin craft sense."),
    ("lexicon", "Dubal remains bark/coolamon/bark container. Do not generalize it to every bowl, bed, coffin, or bark item without context.", "Rule 109: dubal caution carried forward."),
    ("lexicon", "Kanunjul has resin/pitch plus culturally loaded ritual prose. Batch 151 only locates or sees the resin; no ritual claim is generated.", "Rule 109: kanunjul restraint."),
    ("orthography", "Use hyphenated Jina-jina for the water-gum row; unhyphenated jinajina is a reduplication-lint risk and was blocked.", "Rule 109: Jina-jina orthography."),
    ("process", "Exact duplicate preflight matters for flora because several Patz plant examples were already accepted in Rules 91, 103, 107, and later repair batches.", "Rule 109: plant duplicate preflight."),
]

LEXEMES = [
    ("birra", "noun", None, "NA", "leaf; lungs", "batch-151: used only in leaf sense with tree/plant contexts."),
    ("juku", "noun", None, "locative-ngu/ablative-muny", "tree; wood; splinter", "batch-151: tree/wood host and material source rows."),
    ("mayi", "noun", None, "NA", "vegetable food; fruit; food", "batch-151: fruit/vegetable-food sense selected in plant rows."),
    ("dumbul", "noun", None, "NA", "hard covering; bark; crust; shell", "batch-151: shell/hard covering on marra, and bark with wanjakan."),
    ("marra", "noun", None, "locative-nga", "zamia tree; zamia nut; wing", "batch-151: zamia nut/tree sense only."),
    ("dakil-dakil", "noun", None, "NA", "branches of a tree", "batch-151: branch lexeme in juku-ngu frame."),
    ("wakumba", "noun", None, "NA", "canopy; spreading branches of a tree", "batch-151: tree-canopy locative row."),
    ("dingal", "noun", None, "locative-ba", "base of a tree; end", "batch-151: tree-base sense selected."),
    ("jakalkulu", "noun", None, "NA", "tree stump", "batch-151: stump on ground row."),
    ("walmba", "noun", None, "NA", "log", "batch-151: log on ground row."),
    ("dimbirr", "noun", None, "NA", "hollow trunk of a tree", "batch-151: hollow-trunk quality row."),
    ("bindi", "noun", None, "NA", "broad leaf", "batch-151: broad leaf as bag contents."),
    ("kabal", "noun", None, "NA", "Leichhardt tree; Leichhardt fruit", "batch-151: mayi kabal fruit rows."),
    ("bilar", "noun", None, "NA", "candlenut; candle nut tree", "batch-151: roasted candlenut row."),
    ("binainyji", "noun", None, "NA", "fig-like fruit", "batch-151: grammar-added fruit lexeme."),
    ("banday", "noun", None, "NA", "Banday tree; cherry-like fruit", "batch-151: mayi selects fruit sense."),
    ("junjun", "noun", None, "NA", "wild fruit", "batch-151: lexicalized solid reduplicated fruit headword."),
    ("bambayal", "noun", None, "NA", "long thin yam", "batch-151: yam get row."),
    ("banjay", "noun", None, "NA", "small round wild yam", "batch-151: roasted wild-yam row."),
    ("wukay", "noun", None, "NA", "hairy yam", "batch-151: boiled-in-water preparation row; no raw eating claim."),
    ("bangkan", "noun", None, "NA", "medicinal root", "batch-151: boiled-in-water row, source-bound."),
    ("diburr", "noun", None, "NA", "seed; egg; bullet; tablet", "batch-151: seed sense selected by planting/material context."),
    ("kubirr-kubirr", "noun", None, "NA", "black and red seeds", "batch-151: seed quantity row; wankarr not used."),
    ("bilanji", "noun", None, "ablative-muny", "grass used to make dilly bags", "batch-151: bag-weaving material source."),
    ("mawu", "noun", None, "ablative-muny", "coarse grass used in making dilly bags", "batch-151: bag-weaving material source."),
    ("kakan", "noun", None, "ablative-muny", "green upper part of black palm used for dilly bags", "batch-151: prose sense selected over misleading mangrove gloss."),
    ("bajarr", "noun", None, "NA", "loya vine fern leaves", "batch-151: shelter-material collection row."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-151: earth-oven covering row from Text 51."),
    ("dubal", "noun", None, "locative-ba", "bark; coolamon; bark container", "batch-151: bark/chop/container rows, not generic bowl."),
    ("kuralbi", "noun", None, "ablative-muny", "kuralbi tree; wild peasun; bark rope source", "batch-151: rope material row from source prose."),
    ("warrur", "noun", None, "NA", "tree bark usable as vine", "batch-151: material get row."),
    ("ngunyin", "noun", None, "NA", "dillybag; bark strips; web; placenta", "batch-151: weave frame selects craft/bark-strip sense."),
    ("kanunjul", "noun", None, "NA", "grass-tree resin; pitch", "batch-151: resin seen/located, no ritual claim."),
    ("wanjakan", "noun", None, "NA", "ti tree", "batch-151: ti-tree bark at shelter row."),
    ("babajaka", "noun", None, "NA", "bloodwood tree", "batch-151: named tree recognition row."),
    ("bajar", "noun", None, "NA", "Moreton Bay ash; white gum", "batch-151: stand row selects tree sense, not residue ash."),
    ("baril-baril", "noun", None, "NA", "Moreton Bay fig tree", "batch-151: reduplicated named-tree row."),
    ("duwar", "noun", None, "NA", "black palm", "batch-151: palm/tree stand row."),
    ("jina-jina", "noun", None, "NA", "water gum tree", "batch-151: hyphenated Yalanji water-gum form."),
    ("yumu", "noun", None, "NA", "bottlebrush tree", "batch-151: named-tree stand row."),
    ("nganka", "noun", None, "NA", "flower; blossom", "batch-151: flower row with nganjay."),
    ("nganjay", "adjective", None, "NA", "wilted; no good", "batch-151: source phrase nganka nganjay."),
    ("jurrbu", "noun", None, "NA", "plant shoots", "batch-151: shoots quantity row."),
    ("dindal", "verb", "l", "NA", "roast on coals", "batch-151: candlenut and wild-yam roasting."),
    ("wajul", "verb", "l", "NA", "cook; burn; boil in water", "batch-151: bana-nga waju-l boiling frame."),
    ("wukurril", "verb", "l", "NA", "weave; follow; make a fence; imitate", "batch-151: weave sense selected by bag/bark-strip objects."),
    ("nyandal", "verb", "l", "NA", "chop", "batch-151: bark chopping row."),
    ("nyangarril", "verb", "l", "NA", "pour; spill", "batch-151: pour water into bark container."),
    ("nandal", "verb", "l", "NA", "close; shut; bury; plant seed by burying", "batch-151: diburr nandan seed planting usage."),
]


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-151-verify", note, 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 109 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to juku tree/wood sense, birra leaf/lung ambiguity, dubal bark/container limits, "
            "ngunyin craft sense, yibuy/cane carryover, kakan prose-over-gloss, barka exclusion, LOC-vs-ABL plant-part "
            "frames, culturally loaded medicinal/resin entries, named-tree orthography, and exact duplicate avoidance."
        ),
        artifact_path="process_logs/batch-151-plant-materials-process.md",
        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 151: 50 accepted Rule 109 plant/material lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_151.py",
        artifact_path="batch_scripts/close_151.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]
    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-151-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, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
