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

NOTES = (
    "VISIBLE FLORA/TREE SINGULAR/THIRD-PERSON PAST PERCEPTION SWEEP AFTER RULE 305 (Rule 306). "
    "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 ngayu, yundu, nyulu, bula, and jana plus yaluy/yinyay and nyajin. REVIEW: Rule 306 opens only the "
    "singular/third-person past-perception counterpart to the recent nonpast flora/tree fields. 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, nonpast/purposive/reduplicated perception drift, support inflection, or carried "
    "insect/weapon/tool/water/landform/sky/fire/fauna/body/dwelling drift was opened."
)

LESSONS = [
    ("source", "Rule 306 reused ten direct-dictionary flora/tree targets from Rules 303-305: bujabay, jingajalka, jirimandi, julbal, jungka, karranda, karrandal, kawarr, marril, and ngurrkul.", "Rule 306: target inventory."),
    ("source", "Direct dictionary yaml readback was explicit: bujabay lines 3572-3577, jingajalka 9465-9470, jirimandi 9765-9770, julbal 10479-10498, jungka 10893-10910, karranda 13556-13567, karrandal 13568-13579, kawarr 13872-13894, marril 18574-18597, and ngurrkul 23921-23942.", "Rule 306: dictionary source lines."),
    ("source", "Grammar line 2568 supplied Ngayu ... nyaji-ny with gloss see-PAST; Rule 306 uses corpus-conventional nyajin as the past perception support.", "Rule 306: past perception source."),
    ("source", "Living grammar pronoun table lines 2577-2582 supplied bare nominative ngayu, yundu, nyulu, bula, and jana; no accusative, dative, locative, ablative, comitative, possessive, or expanded forms were admitted.", "Rule 306: pronoun table source."),
    ("source", "Living grammar lines 2684-2686 supplied further evidence for second/third person non-singular forms and jana; Rule 306 uses bula as third dual and jana as third plural only.", "Rule 306: third-person support."),
    ("source", "Living grammar demonstrative lines 2834-2845 supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 306: demonstrative 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 306: source-prose caution."),
    ("process", "Rule 306 was scoped as visible flora/tree singular/third-person past perception after Rule 305, not as a plant use, food, medicine, ecology, place/story, material-source, seasonal, or craft field.", "Rule 306: singular/third past flora/tree scope."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 306: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was bujabay 15, jingajalka 15, jirimandi 15, julbal 15, jungka 15, karranda 15, karrandal 15, kawarr 15, marril 15, and ngurrkul 15.", "Rule 306: target coverage audit."),
    ("process", "Support coverage before banking was ngayu 1291, yundu 887, nyulu 562, bula 358, jana 1063, yaluy 3492, yinyay 3744, and nyajin 950.", "Rule 306: support coverage audit."),
    ("lexicon", "Bujabay remained visible bujabay tree only; fruit, edibility, leaching, water, and preparation rows stayed closed.", "Rule 306: bujabay."),
    ("lexicon", "Jingajalka remained visible jingajalka tree only; fruit, bark, basket-making, cooking, hot-stone, bone/death, and use rows stayed closed.", "Rule 306: jingajalka."),
    ("lexicon", "Jirimandi remained visible jirimandi coconut tree only; coconut food, introduced-plant history, and use rows stayed closed.", "Rule 306: jirimandi."),
    ("lexicon", "Julbal remained visible julbal tree only; fruit, food, wet-season, and ripening rows stayed closed.", "Rule 306: julbal."),
    ("lexicon", "Jungka remained visible jungka wild cherry tree only; wild-cherry fruit, food, gathering, and ecology rows stayed closed.", "Rule 306: jungka."),
    ("lexicon", "Karranda remained visible karranda tree only; English-name-unknown source prose did not license any extra predicate.", "Rule 306: karranda."),
    ("lexicon", "Karrandal remained visible karrandal tree only; leaves, white-under colour, crushing, boils, remedy, medicine, and cooking-leaf translation drift stayed closed.", "Rule 306: karrandal."),
    ("lexicon", "Kawarr remained visible kawarr bloodwood tree only; timber, wood, sap, firewood, and source-use rows stayed closed.", "Rule 306: kawarr."),
    ("lexicon", "Marril remained visible marril ti tree only; mangrove expansion, seed, hardwood, oar, water, wood, and use rows stayed closed.", "Rule 306: marril."),
    ("lexicon", "Ngurrkul remained visible ngurrkul fig tree only; fruit, edibility, deep-scrub ecology, and food rows stayed closed.", "Rule 306: ngurrkul."),
    ("morphology", "All Rule 306 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 306: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no singular or third-person accusative, dative, locative, ablative, comitative, possessive, or expanded pronoun forms were admitted.", "Rule 306: bare pronouns."),
    ("morphology", "Yaluy, yinyay, and nyajin stayed uninflected support heads; no demonstrative case, local-derived form, nonpast nyajil, purposive nyaji-nka, reduplicated watching form, or support suffix was admitted.", "Rule 306: uninflected support."),
    ("morphology", "No target compound, source-prose compound, plant-use construction, material-source construction, or productive reduplication was built from the Rule 306 heads.", "Rule 306: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yaluy nyajin for first singular here past visual perception.", "Rule 306: 1sg here band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yinyay nyajin for second singular there past visual perception.", "Rule 306: 2sg there band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yaluy nyajin for third singular here past visual perception.", "Rule 306: 3sg here band."),
    ("syntax", "Rows 31-40 used Bula TARGET yinyay nyajin for third dual there past visual perception.", "Rule 306: 3du there band."),
    ("syntax", "Rows 41-50 used Jana TARGET yaluy nyajin for third plural here past visual perception.", "Rule 306: 3pl here band."),
    ("fidelity", "English stayed literal visual past perception/reference prose: selected subject value, target label, here/there, and saw only.", "Rule 306: 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 306: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual past perception clauses; no harvesting, cooking, treatment, story, seasonal, craft, country-law, mythic narrative, or material-use register was introduced.", "Rule 306: register."),
    ("process", "Rules 149-305 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 306: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,497 if this closes; do not infer plant use, fruit, food, medicine, bark, basket, wood, oar, ecology, place/story, target case, pronoun case, perception compound, nonpast/purposive/reduplicated perception, productive reduplication, or support-inflection grammar from Rule 306.", "Rule 306: next cadence."),
]

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


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-348-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 306 rows. Morphology checked bare flora/tree noun objects, five bare singular/third-person nominative pronoun forms, bare yaluy/yinyay, and nyajin past 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 singular/third-person past-perception bands. Fidelity checked literal visual past 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, nonpast/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 306 lessons covering source checks, singular/third-person 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 306 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 306 accepted", "operator-guide-2026-07-10", 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-348-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 348 / Rule 306 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_348.py", output_excerpt=f"closed batch-348: 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-348: 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())
