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

NOTES = (
    "VISIBLE FLORA/TREE NON-SINGULAR PAST PERCEPTION SWEEP AFTER RULE 307 (Rule 308). "
    "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 nyajin. REVIEW: Rule 308 opens the "
    "first non-singular past flora/tree perception field after the singular/third-person past 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, 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 308 reused ten direct-dictionary flora/tree targets from Rules 303-307: bujabay, jingajalka, jirimandi, julbal, jungka, karranda, karrandal, kawarr, marril, and ngurrkul.", "Rule 308: 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 308: dictionary source lines."),
    ("source", "Grammar line 2568 supplied Ngayu ... nyaji-ny with gloss see-PAST; Rule 308 uses corpus-conventional nyajin as the past perception support.", "Rule 308: past perception source."),
    ("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 308: pronoun table source."),
    ("source", "Living grammar lines 2674-2684 supplied non-singular interpretation: ngali dual exclusive, ngaliny dual inclusive by increment, ngana plural inclusive, and yubal/yurra as second-person non-singular forms.", "Rule 308: non-singular support."),
    ("source", "Living grammar demonstrative lines 2834-2845 supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 308: 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 308: source-prose caution."),
    ("process", "Rule 308 was scoped as visible flora/tree non-singular past perception after Rule 307, not as a plant use, food, medicine, ecology, place/story, material-source, seasonal, or craft field.", "Rule 308: non-singular past flora/tree scope."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 308: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was bujabay 25, jingajalka 25, jirimandi 25, julbal 25, jungka 25, karranda 25, karrandal 25, kawarr 25, marril 25, and ngurrkul 25.", "Rule 308: target coverage audit."),
    ("process", "Support coverage before banking was ngali 463, ngaliny 405, yubal 415, yurra 400, ngana 985, yaluy 3542, yinyay 3794, and nyajin 1050.", "Rule 308: support coverage audit."),
    ("lexicon", "Bujabay remained visible bujabay tree only; fruit, edibility, leaching, water, and preparation rows stayed closed.", "Rule 308: bujabay."),
    ("lexicon", "Jingajalka remained visible jingajalka tree only; fruit, bark, basket-making, cooking, hot-stone, bone/death, and use rows stayed closed.", "Rule 308: jingajalka."),
    ("lexicon", "Jirimandi remained visible jirimandi coconut tree only; coconut food, introduced-plant history, and use rows stayed closed.", "Rule 308: jirimandi."),
    ("lexicon", "Julbal remained visible julbal tree only; fruit, food, wet-season, and ripening rows stayed closed.", "Rule 308: julbal."),
    ("lexicon", "Jungka remained visible jungka wild cherry tree only; wild-cherry fruit, food, gathering, and ecology rows stayed closed.", "Rule 308: jungka."),
    ("lexicon", "Karranda remained visible karranda tree only; English-name-unknown source prose did not license any extra predicate.", "Rule 308: karranda."),
    ("lexicon", "Karrandal remained visible karrandal tree only; leaves, white-under colour, crushing, boils, remedy, medicine, and cooking-leaf translation drift stayed closed.", "Rule 308: karrandal."),
    ("lexicon", "Kawarr remained visible kawarr bloodwood tree only; timber, wood, sap, firewood, and source-use rows stayed closed.", "Rule 308: kawarr."),
    ("lexicon", "Marril remained visible marril ti tree only; mangrove expansion, seed, hardwood, oar, water, wood, and use rows stayed closed.", "Rule 308: marril."),
    ("lexicon", "Ngurrkul remained visible ngurrkul fig tree only; fruit, edibility, deep-scrub ecology, and food rows stayed closed.", "Rule 308: ngurrkul."),
    ("morphology", "All Rule 308 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 308: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no non-singular accusative, dative, locative, ablative, comitative, possessive, third-person, singular, or expanded pronoun forms were admitted.", "Rule 308: 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 308: uninflected support."),
    ("morphology", "No target compound, source-prose compound, plant-use construction, material-source construction, or productive reduplication was built from the Rule 308 heads.", "Rule 308: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yinyay nyajin for first dual exclusive there past visual perception.", "Rule 308: 1du exclusive there band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yaluy nyajin for first dual inclusive here past visual perception.", "Rule 308: 1du inclusive here band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yinyay nyajin for second dual there past visual perception.", "Rule 308: 2du there band."),
    ("syntax", "Rows 31-40 used Yurra TARGET yaluy nyajin for second plural here past visual perception.", "Rule 308: 2pl here band."),
    ("syntax", "Rows 41-50 used Ngana TARGET yinyay nyajin for first plural inclusive there past visual perception.", "Rule 308: 1pl inclusive there band."),
    ("fidelity", "English stayed literal visual past perception/reference prose: selected subject value, target label, here/there, and saw only.", "Rule 308: 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 308: 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 308: register."),
    ("process", "Rules 149-307 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 308: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,597 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 308.", "Rule 308: next cadence."),
]

LEXEMES = [
    ("bujabay", "noun", None, "NA", "bujabay tree", "batch-350: visible bujabay-tree non-singular past perception/reference only; fruit, edibility, leaching, water, and preparation rows closed."),
    ("jingajalka", "noun", None, "NA", "jingajalka tree", "batch-350: visible jingajalka-tree non-singular past perception/reference only; fruit, bark, baskets, cooking, hot stones, bones/death, and use rows closed."),
    ("jirimandi", "noun", None, "NA", "jirimandi coconut tree", "batch-350: visible jirimandi coconut-tree non-singular past perception/reference only; coconut food, introduced-plant history, and use rows closed."),
    ("julbal", "noun", None, "NA", "julbal tree", "batch-350: visible julbal-tree non-singular past perception/reference only; fruit, food, season, and ripening rows closed."),
    ("jungka", "noun", None, "NA", "jungka wild cherry tree", "batch-350: visible jungka wild-cherry-tree non-singular past perception/reference only; fruit, food, gathering, and ecology rows closed."),
    ("karranda", "noun", None, "NA", "karranda tree", "batch-350: visible karranda-tree non-singular past perception/reference only."),
    ("karrandal", "noun", None, "NA", "karrandal tree", "batch-350: visible karrandal-tree non-singular past perception/reference only; leaves, colour, crushing, boils, remedies, medicine, and cooking-leaf translation drift closed."),
    ("kawarr", "noun", None, "NA", "kawarr bloodwood tree", "batch-350: visible kawarr bloodwood-tree non-singular past perception/reference only; timber, wood, sap, firewood, and use rows closed."),
    ("marril", "noun", None, "NA", "marril ti tree", "batch-350: visible marril ti-tree non-singular past perception/reference only; mangrove expansion, seed, hardwood, oars, wood, water, and use rows closed."),
    ("ngurrkul", "noun", None, "NA", "ngurrkul fig tree", "batch-350: visible ngurrkul fig-tree non-singular past perception/reference only; fruit, edibility, food, and ecology rows closed."),
    ("ngali", "pronoun", None, "NA", "first dual exclusive nominative", "batch-350: bare nominative subject support only."),
    ("ngaliny", "pronoun", None, "NA", "first dual inclusive nominative", "batch-350: bare nominative subject support only."),
    ("yubal", "pronoun", None, "NA", "second dual nominative", "batch-350: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-350: bare nominative subject support only."),
    ("ngana", "pronoun", None, "NA", "first plural inclusive nominative", "batch-350: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-350: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-350: bare local demonstrative support only."),
    ("nyajin", "verb-tr", "l", "NA", "saw; see.PAST", "batch-350: 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-350-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 308 rows. Morphology checked bare flora/tree noun objects, five bare non-singular 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 non-singular 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 308 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 308 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 308 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-350-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 350 / Rule 308 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_350.py", output_excerpt=f"closed batch-350: 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-350: 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())
