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

NOTES = (
    "VISIBLE WATER-FAUNA SINGULAR/THIRD PAST PERCEPTION SWEEP AFTER RULE 295 (Rule 296). "
    "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 nyajin. REVIEW: Rule 296 consolidates visible water-fauna "
    "reference only, using a sourced past counterpart to Rule 295 over the same zero-collision target set. 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, nonpast/purposive/reduplicated "
    "perception drift, support inflection, or carried weapon/tool/water/landform/sky/fire/fauna/body/dwelling drift "
    "was opened."
)

LESSONS = [
    ("source", "Rule 296 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 296: 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 296: 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 296: pronoun source."),
    ("source", "Patz demonstrative material supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 296: demonstrative source."),
    ("source", "Patz examples supplied nyaji-ny 'see-PAST', and the tense section supplied past -ny; Rule 296 used corpus-conventional nyajin only.", "Rule 296: past perception source."),
    ("source", "The fish/fauna grammar note was reread as a semantic caution: species names may carry ecological source prose, but Rule 296 uses only visible object reference.", "Rule 296: source-prose caution."),
    ("process", "Rule 296 was scoped as the sourced past counterpart to Rule 295's visible water-fauna singular/third nonpast perception bands, not as a new action or ecology field.", "Rule 296: past counterpart scope."),
    ("process", "Rule 296 retained Rule 295's final target set after the earlier yuday, kulil, and nuwi collision replacement remained closed.", "Rule 296: target-set inheritance."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 296: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was ngawiya 90, ngujay 22, kuyu 436, yawu 31, judi 11, ngalkun 17, kubarr 41, kiju 42, wakal 13, and julul 21.", "Rule 296: target coverage audit."),
    ("process", "Support coverage before banking was ngayu 1251, yundu 847, nyulu 522, bula 318, jana 1023, yaluy 3222, yinyay 3514, and nyajin 650.", "Rule 296: support coverage audit."),
    ("lexicon", "Ngawiya remained visible sea turtle only; hunting, turtle-spearing, cooking, and eating rows stayed closed.", "Rule 296: ngawiya."),
    ("lexicon", "Ngujay remained visible freshwater turtle only; turtle hunting, cooking, and ecology rows stayed closed.", "Rule 296: ngujay."),
    ("lexicon", "Kuyu remained visible generic fish only; catching, spearing, bait, net, cooking, and eating rows stayed closed.", "Rule 296: kuyu."),
    ("lexicon", "Yawu remained visible stingray only; danger, hunting, spearing, and catch rows stayed closed.", "Rule 296: yawu."),
    ("lexicon", "Judi remained visible barramundi only; Nyungkul replacement forms and fishing/cooking rows stayed closed.", "Rule 296: judi."),
    ("lexicon", "Ngalkun remained visible mullet only; fishing, catching, and eating rows stayed closed.", "Rule 296: ngalkun."),
    ("lexicon", "Kubarr remained visible freshwater eel only; colour-property, blackness, fishing, catching, and cooking rows stayed closed.", "Rule 296: kubarr."),
    ("lexicon", "Kiju remained visible mudcrab only; biting, catching, cooking, and warning rows stayed closed.", "Rule 296: kiju."),
    ("lexicon", "Wakal remained visible prawn only; lobster alternation, catching, cooking, and eating rows stayed closed.", "Rule 296: wakal."),
    ("lexicon", "Julul remained visible oyster only; gathering, eating, shore, reef, and ecology rows stayed closed.", "Rule 296: julul."),
    ("morphology", "All Rule 296 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 296: 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 296: bare nominative 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 296: 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 296 heads.", "Rule 296: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yaluy nyajin for first singular here past visual perception.", "Rule 296: 1sg here band."),
    ("syntax", "Rows 11-20 used Yundu TARGET yinyay nyajin for second singular there past visual perception.", "Rule 296: 2sg there band."),
    ("syntax", "Rows 21-30 used Nyulu TARGET yaluy nyajin for third singular here past visual perception.", "Rule 296: 3sg here band."),
    ("syntax", "Rows 31-40 used Bula TARGET yinyay nyajin for third dual there past visual perception.", "Rule 296: 3du there band."),
    ("syntax", "Rows 41-50 used Jana TARGET yaluy nyajin for third plural here past visual perception.", "Rule 296: 3pl here band."),
    ("fidelity", "English stayed literal visual past perception/reference prose: selected subject pronoun value, target label, here/there, and saw only.", "Rule 296: 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 296: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style visual past perception clauses; no fishing narrative, preparation instruction, warning, country-law, mythic narrative, or story register was introduced.", "Rule 296: register."),
    ("process", "Rules 149-295 carry-forward traps stayed closed, especially recent traditional weapon/tool and water-fauna 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 296: carry-forward closure."),
    ("handoff", "Next batch may continue from 16,997 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 296.", "Rule 296: next cadence."),
]

LEXEMES = [
    ("ngawiya", "noun", None, "NA", "sea turtle", "batch-338: visible sea-turtle past perception/reference only; hunting, turtle-spearing, cooking, and eating rows closed."),
    ("ngujay", "noun", None, "NA", "freshwater turtle", "batch-338: visible freshwater-turtle past perception/reference only; hunting, cooking, and ecology rows closed."),
    ("kuyu", "noun", None, "NA", "fish", "batch-338: visible generic-fish past perception/reference only; catching, spearing, bait, net, cooking, and eating rows closed."),
    ("yawu", "noun", None, "NA", "stingray", "batch-338: visible stingray past perception/reference only; danger, hunting, spearing, and catch rows closed."),
    ("judi", "noun", None, "NA", "barramundi", "batch-338: visible barramundi past perception/reference only; Nyungkul replacement forms and fishing/cooking rows closed."),
    ("ngalkun", "noun", None, "NA", "mullet", "batch-338: visible mullet past perception/reference only; fishing, catching, and eating rows closed."),
    ("kubarr", "noun", None, "NA", "freshwater eel", "batch-338: visible freshwater-eel past perception/reference only; colour, fishing, catching, and cooking rows closed."),
    ("kiju", "noun", None, "NA", "mudcrab", "batch-338: visible mudcrab past perception/reference only; biting, catching, cooking, and warning rows closed."),
    ("wakal", "noun", None, "NA", "prawn", "batch-338: visible prawn past perception/reference only; lobster alternation, catching, cooking, and eating rows closed."),
    ("julul", "noun", None, "NA", "oyster", "batch-338: visible oyster past perception/reference only; gathering, eating, shore, reef, and ecology rows closed."),
    ("ngayu", "pronoun", None, "NA", "first singular nominative", "batch-338: bare nominative subject support only."),
    ("yundu", "pronoun", None, "NA", "second singular nominative", "batch-338: bare nominative subject support only."),
    ("nyulu", "pronoun", None, "NA", "third singular nominative", "batch-338: bare nominative subject support only."),
    ("bula", "pronoun", None, "NA", "third dual nominative", "batch-338: bare nominative subject support only."),
    ("jana", "pronoun", None, "NA", "third plural nominative", "batch-338: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-338: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-338: bare local demonstrative support only."),
    ("nyajin", "verb", "l", "NA", "saw", "batch-338: 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-338-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 296 rows. Morphology checked bare water-fauna noun objects, five bare nominative pronoun forms, bare yaluy/yinyay, and nyajin past 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 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 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 296 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 296 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 296 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-338-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 338 / Rule 296 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_338.py", output_excerpt=f"closed batch-338: 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-338: 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())
