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

NOTES = (
    "LOW-COVERAGE VISIBLE TREE/PALM/MANGROVE SINGULAR/THIRD-PERSON NONPAST PERCEPTION SWEEP AFTER RULE 314 "
    "(Rule 315). 50 rows. TARGETS: miyilabu mangrove tree, ngalkarran tree, wada tree, wangku tree, yinkunji fig "
    "tree, yurrunji tree, jajikal screw palm, jalnji tree, jinjay tree, and kurubarr mangrove. SUPPORT: bare "
    "nominative ngayu, yundu, nyulu, bula, and jana plus Yalanji yaluy/yinyay and dictionary-attested nonpast "
    "nyajil. REVIEW: six targets had zero verified token use and four had one before banking. No place-name, camp, "
    "country, story/personification, poison/sap/blindness, fruit/seed/food, wood-goanna homograph, timber/woomera/"
    "spear/gum/material use, ecology, target case, pronoun case, demonstrative case, compounds, past/purposive/"
    "reduplicated perception, support inflection, or carried trap was opened."
)

LESSONS = [
    ("source", "Rule 315 selected ten direct-dictionary low-coverage visible tree/palm/mangrove nouns: six zero-use heads miyilabu, ngalkarran, wada, wangku, yinkunji, and yurrunji, plus four one-use heads jajikal, jalnji, jinjay, and kurubarr.", "Rule 315: low-coverage target inventory."),
    ("source", "Direct dictionary yaml readback was explicit: miyilabu lines 19850-19873, ngalkarran 21896-21917, wada 25015-25036, wangku 26023-26034, yinkunji 30302-30325, yurrunji 31080-31101, jajikal 7027-7069, jalnji 7591-7611, jinjay 9539-9559, and kurubarr 16709-16720.", "Rule 315: dictionary source lines."),
    ("source", "Living grammar pronoun table lines 2577-2586 and demonstrative lines 2834-2847 supplied bare nominatives ngayu, yundu, nyulu, bula, jana and Yalanji yaluy/yinyay; nyulu was selected over the less common free variant yulu.", "Rule 315: pronoun and demonstrative source."),
    ("source", "Patz lines 3043-3049 and 3149-3151 supplied nyaji-l and nonpast function; lines 4256-4265 licensed nominative pronoun A plus bare absolutive O for sensory perception; dictionary lines 24282-24296 independently supplied running-form nyajil and its visual sense.", "Rule 315: nonpast perception and argument source."),
    ("source", "All collateral dictionary prose was treated as a restraint file: place/camp/country, story/personification, poison/sap/blindness, fruit/seed/food, wood goanna, timber/woomera/spear/gum, medicine, material use, and ecology remained closed.", "Rule 315: source-prose caution."),
    ("process", "Rule 315 was scoped as low-coverage bare visible tree/palm/mangrove singular/third-person nonpast perception, not as plant use, food, danger, medicine, material culture, place-name, fauna, story, ecology, or productive morphology.", "Rule 315: bounded lexical-debt scope."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions, and all ten target forms passed the intended-frame linter probe.", "Rule 315: duplicate and form preflight."),
    ("process", "Token-aware target coverage before banking was zero for miyilabu, ngalkarran, wada, wangku, yinkunji, and yurrunji, and one for jajikal, jalnji, jinjay, and kurubarr.", "Rule 315: target coverage audit."),
    ("process", "Support coverage before banking was ngayu 1341, yundu 937, nyulu 612, bula 408, jana 1113, yaluy 3722, yinyay 3964, and nyajil 3797.", "Rule 315: support coverage audit."),
    ("lexicon", "Miyilabu was retained as visible mangrove tree only; poisonous sap, blindness, fish-stupefying, miyil/eye association, use, and ecology rows stayed closed.", "Rule 315: miyilabu."),
    ("lexicon", "Ngalkarran was retained as visible tree only; edible red seed, apple-like fruit, ripening, August-October, food, colour, and season rows stayed closed.", "Rule 315: ngalkarran."),
    ("lexicon", "Wada was retained as visible tree only; smallness predicates, edible white seed, apple-size comparison, ripening, August-October, food, colour, and season rows stayed closed.", "Rule 315: wada."),
    ("lexicon", "Wangku was retained as visible tree only; the wood-goanna/fauna reading, size predicate, habitat, and event rows stayed closed.", "Rule 315: wangku."),
    ("lexicon", "Yinkunji was retained as visible fig tree only; long black fruit, edibility, wet-season ripening, food, colour, shape, and ecology rows stayed closed.", "Rule 315: yinkunji."),
    ("lexicon", "Yurrunji was retained as visible tree only; dead-finish exonym, country distribution, Main camp, Romeo, love/rejection, solitary-tree personification, and story rows stayed closed.", "Rule 315: yurrunji."),
    ("lexicon", "Jajikal was retained as visible screw palm only; Bloomfield/river-mouth/Ayton/lower-camp place senses, abundance, leaves, weaving, and use rows stayed closed.", "Rule 315: jajikal."),
    ("lexicon", "Jalnji was retained as visible tree only; poison, nut/food, human inedibility, gum, spear, material, and use rows stayed closed.", "Rule 315: jalnji."),
    ("lexicon", "Jinjay was retained as visible tree only; nut/fruit, roasting, poisonous smoke/bark/sap, cooked-wattle water, skin cure, food, medicine, and use rows stayed closed.", "Rule 315: jinjay."),
    ("lexicon", "Kurubarr was retained as visible mangrove only; long round seed, shape, fruit, shore/tide ecology, and use rows stayed closed.", "Rule 315: kurubarr."),
    ("morphology", "All ten Rule 315 targets stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 315: bare targets."),
    ("morphology", "All five subject forms stayed bare nominatives: no accusative, dative, locative, ablative, comitative, possessive, expanded pronoun, yulu, or non-selected person/number form was admitted.", "Rule 315: bare pronoun A forms."),
    ("morphology", "Yaluy, yinyay, and nyajil stayed fixed uninflected support heads; no demonstrative case, past nyajin, purposive nyaji-nka, reduplicated watching form, hearing compound, or perception compound was admitted.", "Rule 315: fixed support morphology."),
    ("morphology", "No target compound, source-prose compound, plant-use construction, material-source construction, or productive reduplication was built from Rule 315 heads.", "Rule 315: no compounds or productive reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yinyay nyajil for first singular there nonpast visual perception.", "Rule 315: 1sg there band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yaluy nyajil for second singular here nonpast visual perception.", "Rule 315: 2sg here band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yinyay nyajil for third singular there nonpast visual perception.", "Rule 315: 3sg there band."),
    ("syntax", "Rows 31-40 used Bula TARGET yaluy nyajil for third dual here nonpast visual perception.", "Rule 315: 3du here band."),
    ("syntax", "Rows 41-50 used Jana TARGET yinyay nyajil for third plural there nonpast visual perception.", "Rule 315: 3pl there band."),
    ("fidelity", "English stayed literal present visual perception/reference prose: selected subject value, selected target label, here/there, and see only.", "Rule 315: literal English."),
    ("fidelity", "No dictionary commentary was converted into place, camp, country, story, poison, food, fruit, seed, colour, season, fauna, timber, spear, medicine, material-use, or ecology claims.", "Rule 315: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual nonpast perception clauses; no narrative, cultural instruction, harvesting, preparation, danger, medicine, craft, mythic, or place-name register was introduced.", "Rule 315: register."),
    ("process", "Rule 314's nyajin past-orthography scope remained closed: Rule 315 uses independently attested nonpast nyajil only and does not treat prior past rows as permission for tense or orthographic drift.", "Rule 315: Rule 314 carry-forward closure."),
    ("process", "Every Rule 315 sentence is an explicit row call with exact per-sequence Kuku and English static contracts; no runtime sentence generator authored the batch.", "Rule 315: explicit-row authorship evidence."),
    ("process", "Rules 149-314 carry-forward traps stayed closed, including source-prose, homograph, target-case, pronoun-case, demonstrative-case, perception-compound, target-compound, productive-reduplication, support-inflection, and earlier fauna/tool/water/sky/fire/body/dwelling traps.", "Rule 315: cumulative trap closure."),
    ("handoff", "Next batch may continue from 17,947 if this closes; begin Rule 316 with a fresh source and coverage audit and do not infer any closed place, story, food, poison, fauna, material-use, ecology, case, compound, perception, or support-inflection field from Rule 315.", "Rule 315: next cadence."),
]

LEXEMES = [
    ("miyilabu", "noun", None, "NA", "mangrove tree", "batch-357: visible miyilabu mangrove-tree singular/third-person nonpast perception/reference only; sap, poison, blindness, fish, eye association, use, and ecology closed."),
    ("ngalkarran", "noun", None, "NA", "ngalkarran tree", "batch-357: visible ngalkarran-tree singular/third-person nonpast perception/reference only; seed, fruit, edibility, colour, ripening, month, season, and food closed."),
    ("wada", "noun", None, "NA", "wada tree", "batch-357: visible wada-tree singular/third-person nonpast perception/reference only; size, seed, fruit, edibility, colour, ripening, month, season, and food closed."),
    ("wangku", "noun", None, "NA", "wangku tree", "batch-357: visible wangku-tree singular/third-person nonpast perception/reference only; wood-goanna/fauna homograph, size predicate, habitat, and event closed."),
    ("yinkunji", "noun", None, "NA", "fig tree", "batch-357: visible yinkunji fig-tree singular/third-person nonpast perception/reference only; fruit, shape, colour, edibility, wet-season ripening, food, and ecology closed."),
    ("yurrunji", "noun", None, "NA", "yurrunji tree", "batch-357: visible yurrunji-tree singular/third-person nonpast perception/reference only; exonym, country/place distribution, personification, love/rejection, solitary, and story closed."),
    ("jajikal", "noun", None, "NA", "screw palm", "batch-357: visible jajikal screw-palm singular/third-person nonpast perception/reference only; Bloomfield, river-mouth, Ayton/lower-camp place senses, abundance, leaf, weaving, and use closed."),
    ("jalnji", "noun", None, "NA", "jalnji tree", "batch-357: visible jalnji-tree singular/third-person nonpast perception/reference only; poison, nut/food, inedibility, gum, spear, material, and use closed."),
    ("jinjay", "noun", None, "NA", "jinjay tree", "batch-357: visible jinjay-tree singular/third-person nonpast perception/reference only; fruit/nut, roasting, smoke, poison, bark, sap, water, cure, skin, food, medicine, and use closed."),
    ("kurubarr", "noun", None, "NA", "mangrove", "batch-357: visible kurubarr-mangrove singular/third-person nonpast perception/reference only; seed, shape, fruit, shore/tide ecology, and use closed."),
    ("ngayu", "pronoun", None, "NA", "first singular nominative", "batch-357: bare nominative subject support only."),
    ("yundu", "pronoun", None, "NA", "second singular nominative", "batch-357: bare nominative subject support only."),
    ("nyulu", "pronoun", None, "NA", "third singular nominative", "batch-357: bare nominative subject support only; common variant selected over yulu."),
    ("bula", "pronoun", None, "NA", "third dual nominative", "batch-357: bare nominative subject support only."),
    ("jana", "pronoun", None, "NA", "third plural nominative", "batch-357: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-357: bare Yalanji local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-357: bare Yalanji local demonstrative support only."),
    ("nyajil", "verb-tr", "l", "NA", "see; see.NPST", "batch-357: nonpast visual perception support only; dictionary running form corresponding to Patz nyaji-l."),
]


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, "codex-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-357-verify", note, NOW),
        )

    record_event(db, batch_label=LABEL, phase="lint", event_type="under-review-lint-green", actor="codex", 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="codex", detail="Manual five-lens review passed all 50 Rule 315 rows. Morphology checked bare target O forms, five bare nominative pronoun A forms, yaluy/yinyay, and nonpast nyajil only. Lexicon checked ten direct target senses while closing place, poison, fruit, fauna, story, material-use, and ecology prose. Syntax checked five A-O-local-V bands against Patz sensory-perception argument evidence. Fidelity checked exact subject/target/location/see English contracts. 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="codex", detail="Final review retained no Bloomfield/Ayton/Main-camp/country/story/personification, poison/sap/blindness, fruit/seed/food/colour/season, wood-goanna, timber/woomera/spear/gum/bark/cure/material-use/ecology, target/pronoun/demonstrative case, compound, past/purposive/reduplicated perception, or support-inflection drift.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="review", event_type="lesson-inventory", actor="codex", detail=f"Inserted {len(LESSONS)} Rule 315 lessons covering source checks, coverage debt, selected senses, morphology, syntax, fidelity, register, explicit-row authorship, cumulative traps, and handoff.", artifact_path=PROCESS_LOG, created_at=NOW)
    record_event(db, batch_label=LABEL, phase="review", event_type="lexeme-source-log", actor="codex", detail=f"Inserted {len(LEXEMES)} lexeme/source-log rows for Rule 315 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 315 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-357-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="codex", detail=f"Closed Batch 357 / Rule 315 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_357.py", output_excerpt=f"closed batch-357: 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-357: 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())
