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

NOTES = (
    "VISIBLE WATER-FAUNA NON-SINGULAR NONPAST PERCEPTION SWEEP AFTER RULE 296 (Rule 297). "
    "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 "
    "ngali, ngaliny, yubal, yurra, and ngana plus yaluy/yinyay and nyajil. REVIEW: Rule 297 consolidates visible "
    "water-fauna reference only, using a sourced non-singular nonpast counterpart to Rules 295-296 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, past/purposive/reduplicated perception drift, support inflection, or carried weapon/tool/"
    "water/landform/sky/fire/fauna/body/dwelling drift was opened."
)

LESSONS = [
    ("source", "Rule 297 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 297: 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 297: lexicon 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 297: pronoun source."),
    ("source", "Patz demonstrative material supplied bare local yaluy 'here' and yinyay 'there'; no demonstrative case forms were admitted.", "Rule 297: demonstrative source."),
    ("source", "Patz section 3.8.3.2 supplied nyaji-l 'see', and the tense section supplied nonpast -l; Rule 297 used corpus-conventional nyajil only.", "Rule 297: nonpast perception source."),
    ("source", "The fish/fauna grammar note was reread as a semantic caution: species names may carry ecological source prose, but Rule 297 uses only visible object reference.", "Rule 297: source-prose caution."),
    ("process", "Rule 297 was scoped as the sourced non-singular nonpast counterpart to Rules 295-296's visible water-fauna singular/third perception bands, not as a new action or ecology field.", "Rule 297: non-singular counterpart scope."),
    ("process", "Rule 297 retained Rules 295-296's final target set after earlier yuday, kulil, and nuwi collision replacement remained closed.", "Rule 297: target-set inheritance."),
    ("process", "Final exact preflight over all 50 planned surfaces returned no accepted, revised, or under-review collisions.", "Rule 297: duplicate preflight."),
    ("process", "Token-aware target coverage before banking was ngawiya 95, ngujay 27, kuyu 441, yawu 36, judi 16, ngalkun 22, kubarr 46, kiju 47, wakal 18, and julul 26.", "Rule 297: target coverage audit."),
    ("process", "Support coverage before banking was ngali 403, ngaliny 345, yubal 355, yurra 340, ngana 925, yaluy 3252, yinyay 3534, and nyajil 3397.", "Rule 297: support coverage audit."),
    ("lexicon", "Ngawiya remained visible sea turtle only; hunting, turtle-spearing, cooking, and eating rows stayed closed.", "Rule 297: ngawiya."),
    ("lexicon", "Ngujay remained visible freshwater turtle only; turtle hunting, cooking, and ecology rows stayed closed.", "Rule 297: ngujay."),
    ("lexicon", "Kuyu remained visible generic fish only; catching, spearing, bait, net, cooking, and eating rows stayed closed.", "Rule 297: kuyu."),
    ("lexicon", "Yawu remained visible stingray only; danger, hunting, spearing, and catch rows stayed closed.", "Rule 297: yawu."),
    ("lexicon", "Judi remained visible barramundi only; Nyungkul replacement forms and fishing/cooking rows stayed closed.", "Rule 297: judi."),
    ("lexicon", "Ngalkun remained visible mullet only; fishing, catching, and eating rows stayed closed.", "Rule 297: ngalkun."),
    ("lexicon", "Kubarr remained visible freshwater eel only; colour-property, blackness, fishing, catching, and cooking rows stayed closed.", "Rule 297: kubarr."),
    ("lexicon", "Kiju remained visible mudcrab only; biting, catching, cooking, and warning rows stayed closed.", "Rule 297: kiju."),
    ("lexicon", "Wakal remained visible prawn only; lobster alternation, catching, cooking, and eating rows stayed closed.", "Rule 297: wakal."),
    ("lexicon", "Julul remained visible oyster only; gathering, eating, shore, reef, and ecology rows stayed closed.", "Rule 297: julul."),
    ("morphology", "All Rule 297 target nouns stayed bare absolutive objects: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, plural, derivation, or target suffix was admitted.", "Rule 297: 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 297: bare non-singular 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 297: 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 297 heads.", "Rule 297: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yaluy nyajil for first dual exclusive here nonpast visual perception.", "Rule 297: 1du exclusive here band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yinyay nyajil for first dual inclusive there nonpast visual perception.", "Rule 297: 1du inclusive there band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yaluy nyajil for second dual here nonpast visual perception.", "Rule 297: 2du here band."),
    ("syntax", "Rows 31-40 used Yurra TARGET yinyay nyajil for second plural there nonpast visual perception.", "Rule 297: 2pl there band."),
    ("syntax", "Rows 41-50 used Ngana TARGET yaluy nyajil for first plural inclusive here nonpast visual perception.", "Rule 297: 1pl inclusive here band."),
    ("fidelity", "English stayed literal visual nonpast perception/reference prose: selected subject pronoun value, target label, here/there, and see only.", "Rule 297: 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 297: 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 297: register."),
    ("process", "Rules 149-296 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 297: carry-forward closure."),
    ("handoff", "Next batch may continue from 17,047 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 297.", "Rule 297: next cadence."),
]

LEXEMES = [
    ("ngawiya", "noun", None, "NA", "sea turtle", "batch-339: visible sea-turtle nonpast perception/reference only; hunting, turtle-spearing, cooking, and eating rows closed."),
    ("ngujay", "noun", None, "NA", "freshwater turtle", "batch-339: visible freshwater-turtle nonpast perception/reference only; hunting, cooking, and ecology rows closed."),
    ("kuyu", "noun", None, "NA", "fish", "batch-339: visible generic-fish nonpast perception/reference only; catching, spearing, bait, net, cooking, and eating rows closed."),
    ("yawu", "noun", None, "NA", "stingray", "batch-339: visible stingray nonpast perception/reference only; danger, hunting, spearing, and catch rows closed."),
    ("judi", "noun", None, "NA", "barramundi", "batch-339: visible barramundi nonpast perception/reference only; Nyungkul replacement forms and fishing/cooking rows closed."),
    ("ngalkun", "noun", None, "NA", "mullet", "batch-339: visible mullet nonpast perception/reference only; fishing, catching, and eating rows closed."),
    ("kubarr", "noun", None, "NA", "freshwater eel", "batch-339: visible freshwater-eel nonpast perception/reference only; colour, fishing, catching, and cooking rows closed."),
    ("kiju", "noun", None, "NA", "mudcrab", "batch-339: visible mudcrab nonpast perception/reference only; biting, catching, cooking, and warning rows closed."),
    ("wakal", "noun", None, "NA", "prawn", "batch-339: visible prawn nonpast perception/reference only; lobster alternation, catching, cooking, and eating rows closed."),
    ("julul", "noun", None, "NA", "oyster", "batch-339: visible oyster nonpast perception/reference only; gathering, eating, shore, reef, and ecology rows closed."),
    ("ngali", "pronoun", None, "NA", "first dual exclusive nominative", "batch-339: bare nominative subject support only."),
    ("ngaliny", "pronoun", None, "NA", "first dual inclusive nominative", "batch-339: bare nominative subject support only."),
    ("yubal", "pronoun", None, "NA", "second dual nominative", "batch-339: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-339: bare nominative subject support only."),
    ("ngana", "pronoun", None, "NA", "first plural inclusive nominative", "batch-339: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-339: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-339: bare local demonstrative support only."),
    ("nyajil", "verb-tr", "l", "NA", "see; hear; perceive", "batch-339: 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-339-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 297 rows. Morphology checked bare water-fauna noun objects, five bare non-singular 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 non-singular 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 297 lessons covering source checks, non-singular 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 297 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 297 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-339-verify'").fetchone()[0]
    record_event(db, batch_label=LABEL, phase="close", event_type="close-success", actor="claude-main", detail=f"Closed Batch 339 / Rule 297 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_339.py", output_excerpt=f"closed batch-339: 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-339: 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())
