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

NOTES = (
    "INSECT NON-SINGULAR PAST PERCEPTION SWEEP AFTER RULE 298 (Rule 299). "
    "50 rows. TARGETS: balarr flea, dijaraban mayfly, kalburiji bee, mawal bee, munudumbun scorpion, "
    "munyurri sandfly, nakawarra bee, ngalmnbu jumper ant, yarrka bee, and yiljun grasshopper. SUPPORT: bare "
    "nominative ngali, ngaliny, yubal, yurra, and ngana plus yaluy/yinyay and nyajin. REVIEW: Rule 299 "
    "consolidates visible insect reference only, using a sourced non-singular past counterpart to earlier insect "
    "non-singular nonpast bands over the same zero-collision target set. No biting, stinging, poison, sickness, "
    "honey, nest, eggs, larvae, collecting, edible/food/medicine, seasonal-signal, singing, jumping, antbed, "
    "body/human-body, ecology, danger, event, target case, pronoun case, demonstrative case, target compound, "
    "productive reduplication, perception compound, nonpast/purposive/reduplicated perception drift, support "
    "inflection, or carried weapon/tool/water/landform/sky/fire/fauna/body/dwelling drift was opened."
)

LESSONS = [
    ("source", "Rule 299 selected ten visible insect target heads from the previously source-read Rule 255/256/270/271 inventory: balarr, dijaraban, kalburiji, mawal, munudumbun, munyurri, nakawarra, ngalmnbu, yarrka, and yiljun.", "Rule 299: target inventory."),
    ("source", "Direct dictionary line readback carried forward from the living books was explicit: balarr 833-841, dijaraban 5542-5551, kalburiji 12474-12484, mawal 18743-18753, munudumbun 20816-20826, munyurri 20868-20889, nakawarra 21461-21470, ngalmnbu 21972-21980, yarrka 29551-29559, and yiljun 30019-30029.", "Rule 299: dictionary source lines."),
    ("source", "Patz pronoun tables supplied bare nominative ngali, ngaliny, yubal, yurra, and ngana; no accusative, dative, locative, ablative, comitative, or possessive forms were admitted.", "Rule 299: pronoun source."),
    ("source", "Patz demonstrative material supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 299: demonstrative source."),
    ("source", "Patz examples supplied nyaji-ny 'see-PAST', and the tense section supplied past -ny; Rule 299 used corpus-conventional nyajin only.", "Rule 299: past perception source."),
    ("source", "The insect grammar and errata notes were reread as semantic cautions: species labels may carry source prose about biting, honey, nests, medicine, danger, or seasonal signal, but Rule 299 uses only visible object reference.", "Rule 299: source-prose caution."),
    ("process", "Rule 299 was scoped as the sourced non-singular past counterpart to earlier insect non-singular nonpast perception bands, not as a new action, use, danger, honey, medicine, or ecology field.", "Rule 299: non-singular past counterpart scope."),
    ("process", "Rule 299 retained the Rule 255/256/270/271 final insect target set and did not reopen deferred or rejected insect heads such as diri-diri, dabu, wunba, kuja, yangka, nyirran, karrkil, or malal.", "Rule 299: target-set inheritance."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 299: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was balarr 25, dijaraban 25, kalburiji 25, mawal 25, munudumbun 25, munyurri 25, nakawarra 25, ngalmnbu 25, yarrka 25, and yiljun 25.", "Rule 299: target coverage audit."),
    ("process", "Support coverage before banking was ngali 423, ngaliny 365, yubal 375, yurra 360, ngana 945, yaluy 3312, yinyay 3574, and nyajin 750.", "Rule 299: support coverage audit."),
    ("lexicon", "Balarr remained visible flea only; body, bite, sickness, pest-control, and event rows stayed closed.", "Rule 299: balarr."),
    ("lexicon", "Dijaraban remained visible mayfly only; dragonfly expansion, ecology, and event rows stayed closed.", "Rule 299: dijaraban."),
    ("lexicon", "Kalburiji remained visible kalburiji bee only; honey, nest, egg, larvae, collecting, edible, and source-prose rows stayed closed.", "Rule 299: kalburiji."),
    ("lexicon", "Mawal remained visible mawal bee only; honey, nest, egg, larvae, collecting, edible, and source-prose rows stayed closed.", "Rule 299: mawal."),
    ("lexicon", "Munudumbun remained visible scorpion only; sting, poison, danger, sickness, and event rows stayed closed.", "Rule 299: munudumbun."),
    ("lexicon", "Munyurri remained visible sandfly only; biting, sickness, pest-control, and event rows stayed closed.", "Rule 299: munyurri."),
    ("lexicon", "Nakawarra remained visible nakawarra bee only; honey, nest, collecting, edible, and source-prose rows stayed closed.", "Rule 299: nakawarra."),
    ("lexicon", "Ngalmnbu remained visible jumper ant only; jumping, bite, sting, antbed, and event rows stayed closed.", "Rule 299: ngalmnbu."),
    ("lexicon", "Yarrka remained visible yarrka bee only; smallest, bush, honey, nest, collecting, and source-prose rows stayed closed.", "Rule 299: yarrka."),
    ("lexicon", "Yiljun remained visible grasshopper only; singing, yam-readiness, seasonal-signal, movement, and event rows stayed closed.", "Rule 299: yiljun."),
    ("morphology", "All Rule 299 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 299: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no ngalingan/ngalinka/ngalinda, ngalinyan/ngalinyanka/ngalinyanda, yubalan/yubalanka/yubalanda, yurrangan/yurranka/yurranda, or nganangan/ngananka/ngananda forms were admitted.", "Rule 299: bare non-singular 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 299: uninflected support."),
    ("morphology", "No target compound, ecology compound, body-part compound, use construction, or productive reduplication was built from the Rule 299 heads.", "Rule 299: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yaluy nyajin for first dual exclusive here past visual perception.", "Rule 299: 1du exclusive here band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yinyay nyajin for first dual inclusive there past visual perception.", "Rule 299: 1du inclusive there band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yaluy nyajin for second dual here past visual perception.", "Rule 299: 2du here band."),
    ("syntax", "Rows 31-40 used Yurra TARGET yinyay nyajin for second plural there past visual perception.", "Rule 299: 2pl there band."),
    ("syntax", "Rows 41-50 used Ngana TARGET yaluy nyajin for first plural inclusive here past visual perception.", "Rule 299: 1pl inclusive here band."),
    ("fidelity", "English stayed literal visual past perception/reference prose: selected subject pronoun value, target label, here/there, and saw only.", "Rule 299: literal English."),
    ("fidelity", "The batch did not convert dictionary source prose into biting, stinging, poisoning, sickness, honey, nest, eggs, larvae, medicine, seasonal-signal, movement, danger, ecology, or event claims.", "Rule 299: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual past perception clauses; no warning, treatment, collecting, food-preparation, country-law, mythic narrative, or story register was introduced.", "Rule 299: register."),
    ("process", "Rules 149-298 carry-forward traps stayed closed, especially recent water-fauna traps plus older insect, bird, fish, mammal, reptile, sky, water/landform, fire, body, dwelling, source-prose, homograph, target-case, pronoun-case, demonstrative-case, perception-compound, target-compound, productive-reduplication, and support-inflection traps.", "Rule 299: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,147 if this closes; do not infer insect action, sting, poison, honey, nest, larvae, medicine, seasonal signal, ecology, target case, pronoun case, perception compound, nonpast/purposive/reduplicated perception, productive reduplication, or support-inflection grammar from Rule 299.", "Rule 299: next cadence."),
]

LEXEMES = [
    ("balarr", "noun", None, "NA", "flea", "batch-341: visible flea past perception/reference only; body, bite, sickness, pest-control, and event rows closed."),
    ("dijaraban", "noun", None, "NA", "mayfly", "batch-341: visible mayfly past perception/reference only; dragonfly, ecology, and event rows closed."),
    ("kalburiji", "noun", None, "NA", "kalburiji bee", "batch-341: visible kalburiji-bee past perception/reference only; honey, nest, egg, larvae, collecting, edible, and source-prose rows closed."),
    ("mawal", "noun", None, "NA", "mawal bee", "batch-341: visible mawal-bee past perception/reference only; honey, nest, egg, larvae, collecting, edible, and source-prose rows closed."),
    ("munudumbun", "noun", None, "NA", "scorpion", "batch-341: visible scorpion past perception/reference only; sting, poison, danger, sickness, and event rows closed."),
    ("munyurri", "noun", None, "NA", "sandfly", "batch-341: visible sandfly past perception/reference only; biting, sickness, pest-control, and event rows closed."),
    ("nakawarra", "noun", None, "NA", "nakawarra bee", "batch-341: visible nakawarra-bee past perception/reference only; honey, nest, collecting, edible, and source-prose rows closed."),
    ("ngalmnbu", "noun", None, "NA", "jumper ant", "batch-341: visible jumper-ant past perception/reference only; jumping, bite, sting, antbed, and event rows closed."),
    ("yarrka", "noun", None, "NA", "yarrka bee", "batch-341: visible yarrka-bee past perception/reference only; smallest, bush, honey, nest, collecting, and source-prose rows closed."),
    ("yiljun", "noun", None, "NA", "grasshopper", "batch-341: visible grasshopper past perception/reference only; singing, yam-readiness, seasonal-signal, movement, and event rows closed."),
    ("ngali", "pronoun", None, "NA", "first dual exclusive nominative", "batch-341: bare nominative subject support only."),
    ("ngaliny", "pronoun", None, "NA", "first dual inclusive nominative", "batch-341: bare nominative subject support only."),
    ("yubal", "pronoun", None, "NA", "second dual nominative", "batch-341: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-341: bare nominative subject support only."),
    ("ngana", "pronoun", None, "NA", "first plural inclusive nominative", "batch-341: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-341: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-341: bare local demonstrative support only."),
    ("nyajin", "verb-tr", "l", "NA", "saw; see.PAST", "batch-341: 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-341-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 299 rows. Morphology checked bare insect noun objects, five bare non-singular nominative pronoun forms, bare yaluy/yinyay, and nyajin past only. Lexicon checked selected visible target senses only, with biting/stinging/honey/nest/medicine/danger/ecology closed. Syntax checked five non-singular pronoun 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 deferred/rejected insect heads, no synonym expansion, no sting/bite/poison/sickness/honey/nest/egg/larvae/collecting/edible/medicine/seasonal-signal/singing/jumping/antbed/body/human-body/tree/wood/habitat/ecology/movement/danger/event/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 299 lessons covering source checks, non-singular past 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 299 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 299 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-341-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 341 / Rule 299 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_341.py", output_excerpt=f"closed batch-341: 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-341: 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())
