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

NOTES = (
    "COMPLEMENTARY VISIBLE FLORA/TREE NON-SINGULAR NONPAST PERCEPTION SWEEP AFTER RULE 304 (Rule 305). "
    "50 rows. TARGETS: bujabay tree, jingajalka tree, jirimandi coconut tree, julbal tree, jungka wild cherry tree, "
    "karranda tree, karrandal tree, kawarr bloodwood tree, marril ti tree, and ngurrkul fig tree. SUPPORT: bare "
    "nominative ngali, ngaliny, yubal, yurra, and ngana plus yaluy/yinyay and nyajil. REVIEW: Rule 305 completes the "
    "complementary local-demonstrative half of the flora/tree non-singular nonpast perception field. No fruit, seed, edible/food, "
    "leaching, soaking, water preparation, bark, basket-making, cooking, hot stones, bones/death, wet-season/"
    "ripening, wild-cherry fruit, leaves, colour, crushed leaves, cooking-leaf translation drift, boils, remedies, "
    "medicine, hardwood, oars, mangrove/water expansion, timber, firewood, deep-scrub ecology, place/story, target "
    "case, pronoun case, demonstrative case, target compound, productive reduplication, perception compound, past/"
    "purposive/reduplicated perception drift, support inflection, or carried insect/weapon/tool/water/landform/sky/"
    "fire/fauna/body/dwelling drift was opened."
)

LESSONS = [
    ("source", "Rule 305 reused ten direct-dictionary flora/tree targets from Rule 304: bujabay, jingajalka, jirimandi, julbal, jungka, karranda, karrandal, kawarr, marril, and ngurrkul.", "Rule 305: target inventory."),
    ("source", "Direct dictionary yaml readback was explicit: bujabay lines 3572-3577, jingajalka 9465-9470, jirimandi 9765-9770, julbal 10479-10494, jungka 10893-10906, karranda 13556-13567, karrandal 13568-13579, kawarr 13872-13894, marril 18574-18597, and ngurrkul 23921-23942.", "Rule 305: dictionary source lines."),
    ("source", "Living grammar pronoun table lines 2577-2582 supplied bare nominative ngali, ngaliny, yubal, yurra, and ngana; no accusative, dative, locative, ablative, comitative, possessive, or expanded forms were admitted.", "Rule 305: pronoun table source."),
    ("source", "Living grammar lines 2674-2684 supplied additional non-singular-pronoun evidence: ngali is dual exclusive, ngaliny dual inclusive, yubal/yurra are second-person non-singular, and ngana is plural inclusive.", "Rule 305: non-singular semantics."),
    ("source", "Living grammar demonstrative lines 2834-2845 supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 305: demonstrative source."),
    ("source", "Living grammar verb lines 3043-3051 supplied nyaji-l / nyajil as nonpast perception; Rule 305 used corpus-conventional nyajil only.", "Rule 305: nonpast perception source."),
    ("source", "The flora/tree dictionary prose was reread as a restraint file: fruit, edible, leaching, bark, basket, cooking, medicine, wood, oars, ecology, and place/story prose remained unavailable unless separately opened.", "Rule 305: source-prose caution."),
    ("process", "Rule 305 was scoped as the complementary visible flora/tree non-singular nonpast perception half after Rule 304, not as a plant use, food, medicine, ecology, place/story, material-source, seasonal, or craft field.", "Rule 305: complementary non-singular flora/tree scope."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 305: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was bujabay 10, jingajalka 10, jirimandi 10, julbal 10, jungka 10, karranda 10, karrandal 10, kawarr 10, marril 10, and ngurrkul 10.", "Rule 305: target coverage audit."),
    ("process", "Support coverage before banking was ngali 453, ngaliny 395, yubal 405, yurra 390, ngana 975, yaluy 3462, yinyay 3724, and nyajil 3547.", "Rule 305: support coverage audit."),
    ("lexicon", "Bujabay remained visible bujabay tree only; fruit, edibility, leaching, water, and preparation rows stayed closed.", "Rule 305: bujabay."),
    ("lexicon", "Jingajalka remained visible jingajalka tree only; fruit, bark, basket-making, cooking, hot-stone, bone/death, and use rows stayed closed.", "Rule 305: jingajalka."),
    ("lexicon", "Jirimandi remained visible jirimandi coconut tree only; coconut food, introduced-plant history, and use rows stayed closed.", "Rule 305: jirimandi."),
    ("lexicon", "Julbal remained visible julbal tree only; fruit, food, wet-season, and ripening rows stayed closed.", "Rule 305: julbal."),
    ("lexicon", "Jungka remained visible jungka wild cherry tree only; wild-cherry fruit, food, gathering, and ecology rows stayed closed.", "Rule 305: jungka."),
    ("lexicon", "Karranda remained visible karranda tree only; English-name-unknown source prose did not license any extra predicate.", "Rule 305: karranda."),
    ("lexicon", "Karrandal remained visible karrandal tree only; leaves, white-under colour, crushing, boils, remedy, medicine, and cooking-leaf translation drift stayed closed.", "Rule 305: karrandal."),
    ("lexicon", "Kawarr remained visible kawarr bloodwood tree only; timber, wood, sap, firewood, and source-use rows stayed closed.", "Rule 305: kawarr."),
    ("lexicon", "Marril remained visible marril ti tree only; mangrove expansion, seed, hardwood, oar, water, wood, and use rows stayed closed.", "Rule 305: marril."),
    ("lexicon", "Ngurrkul remained visible ngurrkul fig tree only; fruit, edibility, deep-scrub ecology, and food rows stayed closed.", "Rule 305: ngurrkul."),
    ("morphology", "All Rule 305 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 305: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no non-singular accusative, dative, locative, ablative, comitative, possessive, or expanded pronoun forms were admitted.", "Rule 305: bare pronouns."),
    ("morphology", "Yaluy, yinyay, and nyajil stayed uninflected support heads; no demonstrative case, local-derived form, past nyajin, purposive nyaji-nka, reduplicated watching form, or support suffix was admitted.", "Rule 305: uninflected support."),
    ("morphology", "No target compound, source-prose compound, plant-use construction, material-source construction, or productive reduplication was built from the Rule 305 heads.", "Rule 305: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yaluy nyajil for first dual exclusive here nonpast visual perception.", "Rule 305: 1du exclusive here band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yinyay nyajil for first dual inclusive there nonpast visual perception.", "Rule 305: 1du inclusive there band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yaluy nyajil for second dual here nonpast visual perception.", "Rule 305: 2du here band."),
    ("syntax", "Rows 31-40 used Yurra TARGET yinyay nyajil for second plural there nonpast visual perception.", "Rule 305: 2pl there band."),
    ("syntax", "Rows 41-50 used Ngana TARGET yaluy nyajil for first plural inclusive here nonpast visual perception.", "Rule 305: 1pl inclusive here band."),
    ("fidelity", "English stayed literal visual nonpast perception/reference prose: selected subject value, target label, here/there, and see only.", "Rule 305: literal English."),
    ("fidelity", "The batch did not convert dictionary source prose into fruit, food, leaching, water preparation, bark, basket, cooking, medicine, wood, oar, ecology, place/story, season, or use claims.", "Rule 305: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual nonpast perception clauses; no harvesting, cooking, treatment, story, seasonal, craft, country-law, mythic narrative, or material-use register was introduced.", "Rule 305: register."),
    ("process", "Rules 149-304 carry-forward traps stayed closed, especially recent insect and flora/tree traps plus older weapon/tool, sky, water/landform, fire, fauna, body, dwelling, source-prose, homograph, target-case, pronoun-case, demonstrative-case, perception-compound, target-compound, productive-reduplication, and support-inflection traps.", "Rule 305: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,447 if this closes; do not infer plant use, fruit, food, medicine, bark, basket, wood, oar, ecology, place/story, target case, pronoun case, perception compound, past/purposive/reduplicated perception, productive reduplication, or support-inflection grammar from Rule 305.", "Rule 305: next cadence."),
]

LEXEMES = [
    ("bujabay", "noun", None, "NA", "bujabay tree", "batch-347: visible bujabay-tree non-singular nonpast perception/reference only; fruit, edibility, leaching, water, and preparation rows closed."),
    ("jingajalka", "noun", None, "NA", "jingajalka tree", "batch-347: visible jingajalka-tree non-singular nonpast perception/reference only; fruit, bark, baskets, cooking, hot stones, bones/death, and use rows closed."),
    ("jirimandi", "noun", None, "NA", "jirimandi coconut tree", "batch-347: visible jirimandi coconut-tree non-singular nonpast perception/reference only; coconut food, introduced-plant history, and use rows closed."),
    ("julbal", "noun", None, "NA", "julbal tree", "batch-347: visible julbal-tree non-singular nonpast perception/reference only; fruit, food, season, and ripening rows closed."),
    ("jungka", "noun", None, "NA", "jungka wild cherry tree", "batch-347: visible jungka wild-cherry-tree non-singular nonpast perception/reference only; fruit, food, gathering, and ecology rows closed."),
    ("karranda", "noun", None, "NA", "karranda tree", "batch-347: visible karranda-tree non-singular nonpast perception/reference only."),
    ("karrandal", "noun", None, "NA", "karrandal tree", "batch-347: visible karrandal-tree non-singular nonpast perception/reference only; leaves, colour, crushing, boils, remedies, medicine, and cooking-leaf translation drift closed."),
    ("kawarr", "noun", None, "NA", "kawarr bloodwood tree", "batch-347: visible kawarr bloodwood-tree non-singular nonpast perception/reference only; timber, wood, sap, firewood, and use rows closed."),
    ("marril", "noun", None, "NA", "marril ti tree", "batch-347: visible marril ti-tree non-singular nonpast perception/reference only; mangrove expansion, seed, hardwood, oars, wood, water, and use rows closed."),
    ("ngurrkul", "noun", None, "NA", "ngurrkul fig tree", "batch-347: visible ngurrkul fig-tree non-singular nonpast perception/reference only; fruit, edibility, food, and ecology rows closed."),
    ("ngali", "pronoun", None, "NA", "first dual exclusive nominative", "batch-347: bare nominative subject support only."),
    ("ngaliny", "pronoun", None, "NA", "first dual inclusive nominative", "batch-347: bare nominative subject support only."),
    ("yubal", "pronoun", None, "NA", "second dual nominative", "batch-347: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-347: bare nominative subject support only."),
    ("ngana", "pronoun", None, "NA", "first plural inclusive nominative", "batch-347: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-347: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-347: bare local demonstrative support only."),
    ("nyajil", "verb-tr", "l", "NA", "see; see.NPST", "batch-347: nonpast visual perception support only, corpus-conventional surface from nyaji-l see-NPST."),
]


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 or under_review != 50 or accepted:
        raise SystemExit(f"{LABEL} close precheck failed: total={total}, under_review={under_review}, accepted={accepted}")

    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.execute("DELETE FROM lessons WHERE batch_id=?", (batch_id,))
    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-347-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 305 rows. Morphology checked bare flora/tree noun objects, five bare non-singular nominative pronoun forms, bare yaluy/yinyay, and nyajil nonpast only. Lexicon checked selected visible target senses only, with fruit, food, bark, cooking, medicine, wood, oar, ecology, and place/story source prose closed. Syntax checked five non-singular nonpast-perception bands. Fidelity checked literal visual nonpast reference/perception English. Register stayed plain elicitation-style.", 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 fruit/seed/edible/food/leaching/soaking/water-preparation/bark/basket/cooking/hot-stone/bone/death/wet-season/ripening/wild-cherry-fruit/leaf/colour/crushing/cooking-leaf/boil/remedy/medicine/hardwood/oar/mangrove/water/timber/firewood/deep-scrub-ecology/place/story/source-prose drift, no target case, productive compound, productive reduplication, demonstrative case, pronoun case, perception compound, past/purposive/reduplicated perception drift, or support inflection.", 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 305 lessons covering source checks, non-singular flora/tree scope, coverage, lexical target senses, morphology, syntax, fidelity, register, process traps, and handoff.", artifact_path=PROCESS_LOG, 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 305 targets and support heads.", artifact_path=PROCESS_LOG, created_at=NOW)
    db.execute("UPDATE sentences SET status='accepted', updated_at=? WHERE batch_id=?", (NOW, batch_id))
    db.execute("UPDATE batches SET notes=?, cheatsheet_version=?, guide_version=? WHERE id=?", (NOTES, "Rule 305 accepted", "operator-guide-2026-07-09", batch_id))
    verified_after, words_after = db.execute(
        """
        SELECT COUNT(*), SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    accepted_after = db.execute("SELECT COUNT(*) FROM sentences WHERE batch_id=? AND status='accepted'", (batch_id,)).fetchone()[0]
    review_count = db.execute("SELECT COUNT(*) FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)", (batch_id,)).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-347-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 347 / Rule 305 with {accepted_after} accepted rows, {review_count} review passes, {lesson_count} lessons, and {lexeme_logs} lexeme/source-log rows. Verified sentences moved {verified_before}->{verified_after}; Kuku words moved {words_before}->{words_after}.", command="python3 batch_scripts/close_347.py", output_excerpt=f"closed batch-347: accepted={accepted_after}, reviews={review_count}, lessons={lesson_count}, lexeme_logs={lexeme_logs}, verified {verified_before}->{verified_after}, kuku_words {words_before}->{words_after}", artifact_path=PROCESS_LOG, created_at=NOW)
    db.commit()
    print(
        f"closed batch-347: accepted={accepted_after}, reviews={review_count}, lessons={lesson_count}, "
        f"lexeme_logs={lexeme_logs}, verified {verified_before}->{verified_after}, kuku_words {words_before}->{words_after}"
    )
    return 0


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