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

NOTES = (
    "COMPLEMENTARY VISIBLE TREE/PALM SINGULAR/THIRD-PERSON NONPAST PERCEPTION SWEEP AFTER RULE 310 (Rule 311). "
    "50 rows. TARGETS: dulmbi umbrella palm, kakaji mangrove tree, mukukanka tree, murrkul tree, milbarkal tree, "
    "mirrbangku pencil cedar tree, mura tree, ngadil hickory tree, nyumbil coolibah tree, and wankar tree. "
    "SUPPORT: bare nominative ngayu, yundu, nyulu, bula, and jana plus yaluy/yinyay and nyajil. REVIEW: Rule 311 "
    "keeps the Rule 310 visible tree/palm targets and reverses the local demonstrative slot in singular/third-person "
    "nonpast perception frames. No place-name, timber, woomera, shore/tide ecology, fruit, edible/food, leaching, "
    "poison, date-shape, sweetness, bloom timing, minya jalan, leech/fauna homograph, water-side ecology, flower, "
    "seed, necklace, artefact, material-use, target case, pronoun case, demonstrative case, target compound, "
    "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 311 retained ten direct-dictionary flora/tree targets from Rule 310: dulmbi, kakaji, mukukanka, murrkul, milbarkal, mirrbangku, mura, ngadil, nyumbil, and wankar.", "Rule 311: target inventory."),
    ("source", "Direct dictionary yaml readback was explicit: dulmbi lines 6478-6490, kakaji 12087-12109, mukukanka 20286-20300, murrkul 21058-21070, milbarkal 18981-18990, mirrbangku 19739-19760, mura 20890-20910, ngadil 21677-21697, nyumbil 24727-24748, and wankar 26184-26206.", "Rule 311: dictionary source lines."),
    ("source", "Grammar lines 3043-3049 supplied nyaji-l as the nonpast form of 'see'; Rule 311 uses corpus-conventional nyajil as nonpast perception support.", "Rule 311: nonpast 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 311: pronoun table source."),
    ("source", "Living grammar line 2686 supplied further evidence for third-person dual and plural forms, especially bula and jana; Rule 311 uses them as bare nominative subject supports only.", "Rule 311: 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 311: demonstrative source."),
    ("source", "The tree/palm dictionary prose was reread as a restraint file: place names, timber, woomeras, shore/tide ecology, fruit, leaching, poison, bloom timing, leech homographs, water-side ecology, flowers, seeds, necklaces, artefacts, and material use remained unavailable unless separately opened.", "Rule 311: source-prose caution."),
    ("process", "Rule 311 was scoped as complementary visible tree/palm singular/third-person nonpast perception, not as a plant-use, place-name, material-source, seasonal, ecology, artefact, homograph, or productive-reduplication field.", "Rule 311: complementary tree/palm scope."),
    ("process", "Final exact preflight over all 50 planned complementary surfaces returned no accepted, revised, or under-review collisions.", "Rule 311: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was five for all ten selected target heads after Rule 310: dulmbi, kakaji, mukukanka, murrkul, milbarkal, mirrbangku, mura, ngadil, nyumbil, and wankar.", "Rule 311: target coverage audit."),
    ("process", "Support coverage before banking was ngayu 1321, yundu 917, nyulu 592, bula 388, jana 1093, yaluy 3622, yinyay 3864, and nyajil 3647.", "Rule 311: support coverage audit."),
    ("lexicon", "Dulmbi was retained as visible umbrella palm only; the place at Stucky's Gap reading stayed closed.", "Rule 311: dulmbi."),
    ("lexicon", "Kakaji was retained as visible mangrove-tree reference only; fruit, leaching, poison, shore, tide, use, and ecology rows stayed closed.", "Rule 311: kakaji."),
    ("lexicon", "Mukukanka was retained as visible mukukanka tree only; fruit, edible, food, ripening, month, season, and use rows stayed closed.", "Rule 311: mukukanka."),
    ("lexicon", "Murrkul was retained as visible murrkul tree only; fruit, edible, food, seed, season, and use rows stayed closed.", "Rule 311: murrkul."),
    ("lexicon", "Milbarkal was retained as visible milbarkal tree only; English-name-unknown source prose did not license extra predicates.", "Rule 311: milbarkal."),
    ("lexicon", "Mirrbangku was retained as visible pencil cedar tree only; fruit, date-shape, sweetness, and food rows stayed closed.", "Rule 311: mirrbangku."),
    ("lexicon", "Mura was retained as visible mura tree only; bloom timing, minya jalan, season, and event rows stayed closed.", "Rule 311: mura."),
    ("lexicon", "Ngadil was retained as visible hickory tree only; timber, woomera, and material-use rows stayed closed.", "Rule 311: ngadil."),
    ("lexicon", "Nyumbil was retained as visible coolibah tree only; the leech/fauna homograph stayed closed.", "Rule 311: nyumbil."),
    ("lexicon", "Wankar was retained as visible wankar tree only; water-side ecology, flowers, seeds, necklace, and artefact rows stayed closed.", "Rule 311: wankar."),
    ("morphology", "All Rule 311 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 311: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no singular or third-person accusative, dative, locative, ablative, comitative, possessive, expanded pronoun, or alternative yulu/iana form was admitted.", "Rule 311: 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 311: uninflected support."),
    ("morphology", "No target compound, source-prose compound, plant-use construction, material-source construction, or productive reduplication was built from the Rule 311 heads.", "Rule 311: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yinyay nyajil for first singular there nonpast visual perception.", "Rule 311: 1sg there band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yaluy nyajil for second singular here nonpast visual perception.", "Rule 311: 2sg here band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yinyay nyajil for third singular there nonpast visual perception.", "Rule 311: 3sg there band."),
    ("syntax", "Rows 31-40 used Bula TARGET yaluy nyajil for third dual here nonpast visual perception.", "Rule 311: 3du here band."),
    ("syntax", "Rows 41-50 used Jana TARGET yinyay nyajil for third plural there nonpast visual perception.", "Rule 311: 3pl there band."),
    ("fidelity", "English stayed literal visual nonpast perception/reference prose: selected subject value, target label, here/there, and see/sees only.", "Rule 311: literal English."),
    ("fidelity", "The batch did not convert dictionary source prose into place-name, timber, woomera, shore/tide ecology, fruit, leaching, poison, bloom, season, homograph, ecology, flower, seed, necklace, artefact, or material-use claims.", "Rule 311: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual nonpast perception clauses; no harvesting, making, story, seasonal, craft, country-law, mythic narrative, material-use, or place-name register was introduced.", "Rule 311: register."),
    ("process", "Rules 149-310 carry-forward traps stayed closed, especially recent flora/tree perception traps plus older insect, 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 311: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,747 if this closes; do not infer plant use, place-name, timber, woomera, shore/tide ecology, fruit, bloom timing, homograph, ecology, artefact, target case, pronoun case, perception compound, past/purposive/reduplicated perception, productive reduplication, or support-inflection grammar from Rule 311.", "Rule 311: next cadence."),
]

LEXEMES = [
    ("dulmbi", "noun", None, "NA", "umbrella palm", "batch-353: complementary visible dulmbi umbrella-palm nonpast perception/reference only; place-name use closed."),
    ("kakaji", "noun", None, "NA", "mangrove tree", "batch-353: complementary visible kakaji mangrove-tree nonpast perception/reference only; fruit, leaching, poison, shore, tide, use, and ecology rows closed."),
    ("mukukanka", "noun", None, "NA", "mukukanka tree", "batch-353: complementary visible mukukanka-tree nonpast perception/reference only; fruit, edible, food, ripening, month, season, and use rows closed."),
    ("murrkul", "noun", None, "NA", "murrkul tree", "batch-353: complementary visible murrkul-tree nonpast perception/reference only; fruit, edible, food, seed, season, and use rows closed."),
    ("milbarkal", "noun", None, "NA", "milbarkal tree", "batch-353: complementary visible milbarkal-tree nonpast perception/reference only."),
    ("mirrbangku", "noun", None, "NA", "pencil cedar tree", "batch-353: complementary visible mirrbangku pencil-cedar-tree nonpast perception/reference only; fruit, date-shape, sweetness, and food rows closed."),
    ("mura", "noun", None, "NA", "mura tree", "batch-353: complementary visible mura-tree nonpast perception/reference only; bloom timing, minya jalan, season, and event rows closed."),
    ("ngadil", "noun", None, "NA", "hickory tree", "batch-353: complementary visible ngadil hickory-tree nonpast perception/reference only; timber, woomera, and material-use rows closed."),
    ("nyumbil", "noun", None, "NA", "coolibah tree", "batch-353: complementary visible nyumbil coolibah-tree nonpast perception/reference only; leech/fauna homograph closed."),
    ("wankar", "noun", None, "NA", "wankar tree", "batch-353: complementary visible wankar-tree nonpast perception/reference only; water-side ecology, flowers, seeds, necklace, and artefact rows closed."),
    ("ngayu", "pronoun", None, "NA", "first singular nominative", "batch-353: bare nominative subject support only."),
    ("yundu", "pronoun", None, "NA", "second singular nominative", "batch-353: bare nominative subject support only."),
    ("nyulu", "pronoun", None, "NA", "third singular nominative", "batch-353: bare nominative subject support only."),
    ("bula", "pronoun", None, "NA", "third dual nominative", "batch-353: bare nominative subject support only."),
    ("jana", "pronoun", None, "NA", "third plural nominative", "batch-353: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-353: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-353: bare local demonstrative support only."),
    ("nyajil", "verb-tr", "l", "NA", "see; see.NPST", "batch-353: 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-353-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 311 rows. Morphology checked bare tree/palm noun objects, five bare singular/third-person nominative pronoun forms, bare yaluy/yinyay, and nyajil nonpast only. Lexicon checked selected visible target senses only, with place-name, timber, woomera, shore/tide ecology, fruit, leaching, poison, bloom, leech, necklace, artefact, and source prose closed. Syntax checked five complementary singular/third-person 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 place-name/timber/woomera/shore-tide-ecology/fruit/leaching/poison/date-shape/sweetness/bloom/minya-jalan/leech-fauna/water-side-ecology/flower/seed/necklace/artefact/material-use/source-prose drift, no target case, productive compound, 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 311 lessons covering source checks, complementary tree/palm 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 311 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 311 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-353-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 353 / Rule 311 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_353.py", output_excerpt=f"closed batch-353: 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-353: 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())
