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

NOTES = (
    "VISIBLE WATER-FAUNA SINGULAR/THIRD NONPAST PERCEPTION SWEEP AFTER RULE 294 (Rule 295). "
    "50 rows. TARGETS: ngawiya sea turtle, ngujay freshwater turtle, kuyu fish, yawu stingray, judi barramundi, "
    "ngalkun mullet, kubarr freshwater eel, kiju mudcrab, wakal prawn, and julul oyster. SUPPORT: bare nominative "
    "ngayu, yundu, nyulu, bula, and jana plus yaluy/yinyay and nyajil. REVIEW: Rule 295 opens visible water-fauna "
    "reference only, using a fresh zero-collision target set after yuday/kulil/nuwi collision preflight. No catching, "
    "spearing, hunting, cooking, eating, bait, net, hook, danger, ecology, place/story, target case, pronoun case, "
    "demonstrative case, target compound, productive reduplication, perception compound, past/purposive/reduplicated "
    "perception drift, support inflection, or carried weapon/tool/water/landform/sky/fire/fauna/body/dwelling drift "
    "was opened."
)

LESSONS = [
    ("source", "Rule 295 selected ten visible water-fauna target heads from the core dictionary-derived lexicon: ngawiya, ngujay, kuyu, yawu, judi, ngalkun, kubarr, kiju, wakal, and julul.", "Rule 295: target inventory."),
    ("source", "Direct lexicon line readback was explicit: ngawiya 744, ngujay 745, kuyu 751, yawu 753, judi 754, ngalkun 755, kubarr 756, kiju 757, wakal 758, and julul 759.", "Rule 295: lexicon source lines."),
    ("source", "Patz pronoun tables supplied bare nominative ngayu, yundu, nyulu, bula, and jana; no singular accusative, dative, or possessive forms were admitted.", "Rule 295: pronoun source."),
    ("source", "Patz demonstrative material supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 295: demonstrative source."),
    ("source", "Patz section 3.8.3.2 supplied nyaji-l 'see', and the tense section supplied nonpast -l; Rule 295 used corpus-conventional nyajil only.", "Rule 295: nonpast perception source."),
    ("source", "The fish/fauna grammar note was reread as a semantic caution: species names may carry ecological source prose, but Rule 295 uses only visible object reference.", "Rule 295: source-prose caution."),
    ("process", "Rule 295 was scoped as a fresh lexical-field audit after the traditional weapon/tool sequence, not as a continuation of weapon/tool action semantics.", "Rule 295: fresh field scope."),
    ("process", "Initial candidate preflight found exact collisions for yuday, kulil, and nuwi surfaces; those targets were removed before banking.", "Rule 295: collision replacement."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 295: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was ngawiya 85, ngujay 17, kuyu 431, yawu 26, judi 6, ngalkun 12, kubarr 36, kiju 37, wakal 8, and julul 16.", "Rule 295: target coverage audit."),
    ("process", "Support coverage before banking was ngayu 1241, yundu 837, nyulu 512, bula 308, jana 1013, yaluy 3192, yinyay 3494, and nyajil 3347.", "Rule 295: support coverage audit."),
    ("lexicon", "Ngawiya remained visible sea turtle only; hunting, turtle-spearing, cooking, and eating rows stayed closed.", "Rule 295: ngawiya."),
    ("lexicon", "Ngujay remained visible freshwater turtle only; turtle hunting, cooking, and ecology rows stayed closed.", "Rule 295: ngujay."),
    ("lexicon", "Kuyu remained visible generic fish only; catching, spearing, bait, net, cooking, and eating rows stayed closed.", "Rule 295: kuyu."),
    ("lexicon", "Yawu remained visible stingray only; danger, hunting, spearing, and catch rows stayed closed.", "Rule 295: yawu."),
    ("lexicon", "Judi remained visible barramundi only; Nyungkul replacement forms and fishing/cooking rows stayed closed.", "Rule 295: judi."),
    ("lexicon", "Ngalkun remained visible mullet only; fishing, catching, and eating rows stayed closed.", "Rule 295: ngalkun."),
    ("lexicon", "Kubarr remained visible freshwater eel only; colour-property, blackness, fishing, catching, and cooking rows stayed closed.", "Rule 295: kubarr."),
    ("lexicon", "Kiju remained visible mudcrab only; biting, catching, cooking, and warning rows stayed closed.", "Rule 295: kiju."),
    ("lexicon", "Wakal remained visible prawn only; lobster alternation, catching, cooking, and eating rows stayed closed.", "Rule 295: wakal."),
    ("lexicon", "Julul remained visible oyster only; gathering, eating, shore, reef, and ecology rows stayed closed.", "Rule 295: julul."),
    ("morphology", "All Rule 295 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 295: bare targets."),
    ("morphology", "All five subject support forms stayed bare nominatives: no ngaykunku/yununku/nyungunku possessive/dative stems or bula/jana case forms were admitted.", "Rule 295: bare nominative 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 295: uninflected support."),
    ("morphology", "No target compound, ecology compound, place-name compound, body-part compound, object-use construction, or productive reduplication was built from the Rule 295 heads.", "Rule 295: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yaluy nyajil for first singular here nonpast visual perception.", "Rule 295: 1sg here band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yinyay nyajil for second singular there nonpast visual perception.", "Rule 295: 2sg there band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yaluy nyajil for third singular here nonpast visual perception.", "Rule 295: 3sg here band."),
    ("syntax", "Rows 31-40 used Bula TARGET yinyay nyajil for third dual there nonpast visual perception.", "Rule 295: 3du there band."),
    ("syntax", "Rows 41-50 used Jana TARGET yaluy nyajil for third plural here nonpast visual perception.", "Rule 295: 3pl here band."),
    ("fidelity", "English stayed literal visual nonpast perception/reference prose: selected subject pronoun value, target label, here/there, and see only.", "Rule 295: literal English."),
    ("fidelity", "The batch did not convert dictionary source prose into hunting, catching, spearing, cooking, eating, danger, ecology, shore, reef, story, or place claims.", "Rule 295: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual nonpast perception clauses; no fishing narrative, preparation instruction, warning, country-law, mythic narrative, or story register was introduced.", "Rule 295: register."),
    ("process", "Rules 149-294 carry-forward traps stayed closed, especially recent traditional weapon/tool traps plus older fish/fauna, 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 295: carry-forward closure."),
    ("handoff", "Next batch may continue from 16,947 if this closes; do not infer fish action, turtle spearing, hunting, catching, cooking, eating, danger, ecology, target case, pronoun case, perception compound, past/purposive/reduplicated perception, productive reduplication, or support-inflection grammar from Rule 295.", "Rule 295: next cadence."),
]

LEXEMES = [
    ("ngawiya", "noun", None, "NA", "sea turtle", "batch-337: visible sea-turtle nonpast perception/reference only; hunting, turtle-spearing, cooking, and eating rows closed."),
    ("ngujay", "noun", None, "NA", "freshwater turtle", "batch-337: visible freshwater-turtle nonpast perception/reference only; hunting, cooking, and ecology rows closed."),
    ("kuyu", "noun", None, "NA", "fish", "batch-337: visible generic-fish nonpast perception/reference only; catching, spearing, bait, net, cooking, and eating rows closed."),
    ("yawu", "noun", None, "NA", "stingray", "batch-337: visible stingray nonpast perception/reference only; danger, hunting, spearing, and catch rows closed."),
    ("judi", "noun", None, "NA", "barramundi", "batch-337: visible barramundi nonpast perception/reference only; Nyungkul replacement forms and fishing/cooking rows closed."),
    ("ngalkun", "noun", None, "NA", "mullet", "batch-337: visible mullet nonpast perception/reference only; fishing, catching, and eating rows closed."),
    ("kubarr", "noun", None, "NA", "freshwater eel", "batch-337: visible freshwater-eel nonpast perception/reference only; colour, fishing, catching, and cooking rows closed."),
    ("kiju", "noun", None, "NA", "mudcrab", "batch-337: visible mudcrab nonpast perception/reference only; biting, catching, cooking, and warning rows closed."),
    ("wakal", "noun", None, "NA", "prawn", "batch-337: visible prawn nonpast perception/reference only; lobster alternation, catching, cooking, and eating rows closed."),
    ("julul", "noun", None, "NA", "oyster", "batch-337: visible oyster nonpast perception/reference only; gathering, eating, shore, reef, and ecology rows closed."),
    ("ngayu", "pronoun", None, "NA", "first singular nominative", "batch-337: bare nominative subject support only."),
    ("yundu", "pronoun", None, "NA", "second singular nominative", "batch-337: bare nominative subject support only."),
    ("nyulu", "pronoun", None, "NA", "third singular nominative", "batch-337: bare nominative subject support only."),
    ("bula", "pronoun", None, "NA", "third dual nominative", "batch-337: bare nominative subject support only."),
    ("jana", "pronoun", None, "NA", "third plural nominative", "batch-337: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-337: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-337: bare local demonstrative support only."),
    ("nyajil", "verb", "l", "NA", "see", "batch-337: nonpast visual perception support only, corpus-conventional surface from nyaji-l see-NONPAST."),
]


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-337-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 295 rows. Morphology checked bare water-fauna noun objects, five bare nominative pronoun forms, bare yaluy/yinyay, and nyajil nonpast only. Lexicon checked selected visible target senses only, with catching/spearing/hunting/cooking/eating/danger/ecology closed. Syntax checked five singular/third-person pronoun-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 yuday/kulil/nuwi collided surfaces, no shark/ray danger extension, no turtle-spearing, hunting, catching, cooking, eating, bait, net, hook, ecology, shore, reef, place/story, colour-property, target case, productive compound, productive reduplication, 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 295 lessons covering source checks, collision replacement, 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 295 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 295 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-337-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 337 / Rule 295 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_337.py", output_excerpt=f"closed batch-337: 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-337: 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())
