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

NOTES = (
    "COMPLEMENTARY INSECT NON-SINGULAR PAST PERCEPTION SWEEP AFTER RULE 299 (Rule 300). "
    "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 complementary yaluy/yinyay and nyajin. REVIEW: Rule 300 "
    "completes the here/there complement of Rule 299's visible insect non-singular past bands over the same "
    "zero-collision target set. No biting, stinging, poison, sickness, vomiting, honey, nest, eggs, larvae, "
    "collecting, edible/food/medicine, seasonal-signal, singing, jumping, antbed, body/human-body, tree/wood, "
    "ecology, movement, 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 300 retained the ten direct-dictionary insect targets from Rule 299: balarr, dijaraban, kalburiji, mawal, munudumbun, munyurri, nakawarra, ngalmnbu, yarrka, and yiljun.", "Rule 300: target inventory."),
    ("source", "Direct dictionary yaml readback was explicit: balarr line 833, dijaraban 5542, kalburiji 12474, mawal 18743, munudumbun 20816, munyurri 20868, nakawarra 21461, ngalmnbu 21972, yarrka 29551, and yiljun 30019.", "Rule 300: dictionary source lines."),
    ("source", "Living grammar pronoun tables supplied bare nominative ngali, ngaliny, yubal, yurra, and ngana; no accusative, dative, locative, ablative, comitative, possessive, or expanded non-singular forms were admitted.", "Rule 300: pronoun source."),
    ("source", "Living grammar demonstrative notes supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 300: demonstrative source."),
    ("source", "Patz examples and living grammar supplied nyaji-ny / nyajin as past perception; Rule 300 used corpus-conventional nyajin only.", "Rule 300: past perception source."),
    ("source", "The insect dictionary prose was reread as a restraint file: synonym, dragonfly, smallest-bush, singing/yam, honey/nest, and danger prose remained unavailable unless separately opened.", "Rule 300: source-prose caution."),
    ("process", "Rule 300 was scoped as the complementary here/there half of Rule 299, not as a new insect action, use, danger, medicine, honey, nesting, food, ecology, or seasonal-signal field.", "Rule 300: complementary scope."),
    ("process", "Rule 300 retained Rule 299's target set and did not reopen deferred or rejected insect heads such as munukurru, diri-diri, dabu, wunba, kuja, yangka, nyirran, karrkil, murma, or malal.", "Rule 300: target-set inheritance."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 300: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was balarr 30, dijaraban 30, kalburiji 30, mawal 30, munudumbun 30, munyurri 30, nakawarra 30, ngalmnbu 30, yarrka 30, and yiljun 30.", "Rule 300: target coverage audit."),
    ("process", "Support coverage before banking was ngali 433, ngaliny 375, yubal 385, yurra 370, ngana 955, yaluy 3342, yinyay 3594, and nyajin 800.", "Rule 300: support coverage audit."),
    ("lexicon", "Balarr remained visible flea only; body, bite, sickness, pest-control, and event rows stayed closed.", "Rule 300: balarr."),
    ("lexicon", "Dijaraban remained visible mayfly only; dragonfly expansion, ecology, and event rows stayed closed.", "Rule 300: dijaraban."),
    ("lexicon", "Kalburiji remained visible kalburiji bee only; honey, nest, egg, larvae, collecting, edible, and source-prose rows stayed closed.", "Rule 300: kalburiji."),
    ("lexicon", "Mawal remained visible mawal bee only; honey, nest, egg, larvae, collecting, edible, and source-prose rows stayed closed.", "Rule 300: mawal."),
    ("lexicon", "Munudumbun remained visible scorpion only; munukurru, sting, poison, danger, sickness, and event rows stayed closed.", "Rule 300: munudumbun."),
    ("lexicon", "Munyurri remained visible sandfly only; diri-diri, biting, sickness, pest-control, and event rows stayed closed.", "Rule 300: munyurri."),
    ("lexicon", "Nakawarra remained visible nakawarra bee only; honey, nest, collecting, edible, and source-prose rows stayed closed.", "Rule 300: nakawarra."),
    ("lexicon", "Ngalmnbu remained visible jumper ant only; jumping, bite, sting, antbed, and event rows stayed closed.", "Rule 300: ngalmnbu."),
    ("lexicon", "Yarrka remained visible yarrka bee only; smallest, bush, honey, nest, collecting, and source-prose rows stayed closed.", "Rule 300: yarrka."),
    ("lexicon", "Yiljun remained visible grasshopper only; singing, yam-readiness, seasonal-signal, movement, and event rows stayed closed.", "Rule 300: yiljun."),
    ("morphology", "All Rule 300 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 300: 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 300: 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 300: uninflected support."),
    ("morphology", "No target compound, source-prose compound, body-part compound, use construction, or productive reduplication was built from the Rule 300 heads.", "Rule 300: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yinyay nyajin for first dual exclusive there past visual perception.", "Rule 300: 1du exclusive there band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yaluy nyajin for first dual inclusive here past visual perception.", "Rule 300: 1du inclusive here band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yinyay nyajin for second dual there past visual perception.", "Rule 300: 2du there band."),
    ("syntax", "Rows 31-40 used Yurra TARGET yaluy nyajin for second plural here past visual perception.", "Rule 300: 2pl here band."),
    ("syntax", "Rows 41-50 used Ngana TARGET yinyay nyajin for first plural inclusive there past visual perception.", "Rule 300: 1pl inclusive there band."),
    ("fidelity", "English stayed literal visual past perception/reference prose: selected subject pronoun value, target label, here/there, and saw only.", "Rule 300: literal English."),
    ("fidelity", "The batch did not convert dictionary source prose into biting, stinging, poisoning, sickness, vomiting, honey, nest, eggs, larvae, medicine, seasonal-signal, movement, danger, ecology, or event claims.", "Rule 300: 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 300: register."),
    ("process", "Rules 149-299 carry-forward traps stayed closed, especially recent water-fauna and insect 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 300: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,197 if this closes; do not infer insect action, bite, 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 300.", "Rule 300: next cadence."),
]

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