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

NOTES = (
    "FISH-REFERENCE PERCEPTION DEBT SWEEP AFTER RULE 239 (Rule 240). 50 rows. TARGETS: kubija "
    "barracuda, mujarrka archerfish, barrbal black bream, wuyumbu toadfish, bayil perch, dalmbal flathead, "
    "balarri queenfish, bilmbin black-tip shark, jalkay salmon, and jijirr red bream. SUPPORT: bare "
    "nominative ngayu, nyulu, yurra, bula, and jana plus yaluy/yinyay and nyajil. FRAMES: Ngayu TARGET "
    "yinyay nyajil, Nyulu TARGET yaluy nyajil, Yurra TARGET yinyay nyajil, Bula TARGET yaluy nyajil, "
    "and Jana TARGET yinyay nyajil. REVIEW: no bayilbayil unhyphenated reduplication, kijukum illegal-coda "
    "form, ngiwa moray-eel/sea-snake/place/story-site homograph, yidilnyul Nyungkul-only manta form, catching, "
    "netting, hook/line, spearing, eating, cooking, bait, taboo, storm/thunder, story/place, water/river/sea/"
    "reef/habitat, fish body-part, colour predicate, target case, target compound, productive reduplication, "
    "pronoun case, perception compound, support inflection, walarrji rhotic-palatal-lint drift, or recent dwelling/"
    "fire/body drift was opened."
)

LESSONS = [
    ("source", "Rule 240 selected ten checked fish-reference noun heads: kubija, mujarrka, barrbal, wuyumbu, bayil, dalmbal, balarri, bilmbin, jalkay, and jijirr.", "Rule 240: target inventory."),
    ("source", "Patz section 3.1.2 supports nouns as terms for fauna and other corporeal objects; Rule 240 uses species-label reference only and does not use kuyu as a target classifier.", "Rule 240: noun source."),
    ("source", "Patz section 3.5 Table 3.6 supplied the bare nominative pronoun forms ngayu, nyulu, yurra, bula, and jana used as subject support in this batch.", "Rule 240: pronoun source."),
    ("source", "Patz section 3.7 supplied yaluy 'here' and yinyay 'there'; Rule 240 used only the bare local demonstratives.", "Rule 240: demonstrative source."),
    ("source", "Patz section 3.8.3.2 supplied nyaji-l 'see'; Rule 240 used only the nonpast form nyajil and did not build perception compounds or purposive rows.", "Rule 240: perception source."),
    ("process", "Hard exclusions retained: bayilbayil after unhyphenated-reduplication lint, kijukum after illegal-final-coda lint, ngiwa because of sea-snake/place/story-site homography, yidilnyul because it is marked Nyungkul with Yalanji yalnganji, and walarrji after the current under-review rhotic-palatal lint rejection.", "Rule 240: hard exclusions."),
    ("process", "Exact duplicate preflight over all 50 planned Rule 240 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 240: duplicate preflight."),
    ("process", "Token-boundary coverage before banking was kubija 0, mujarrka 0, barrbal 6, wuyumbu 0, bayil 1, dalmbal 1, balarri 3, bilmbin 3, jalkay 6, and jijirr 6.", "Rule 240: coverage audit."),
    ("lexicon", "Kubija was admitted as barracuda only; garfish alternate, water, catching, and habitat prose stayed closed.", "Rule 240: kubija."),
    ("lexicon", "Mujarrka was admitted as archerfish only; Yalanji status was retained, while spotted-Jewfish, Nyungkul dalku, and habitat prose stayed closed.", "Rule 240: mujarrka."),
    ("lexicon", "Barrbal was admitted as black bream only; catching, eating, water, reef/habitat, colour, and event prose stayed closed.", "Rule 240: barrbal."),
    ("lexicon", "Wuyumbu was admitted as toadfish only; striped-toby and generic-fish prose stayed closed.", "Rule 240: wuyumbu."),
    ("lexicon", "Bayil was admitted as perch only; jungle/freshwater expansion, catching, eating, and habitat prose stayed closed.", "Rule 240: bayil."),
    ("lexicon", "Dalmbal was admitted as flathead only; dukul-barangka synonym, compound analysis, catching, and food prose stayed closed.", "Rule 240: dalmbal."),
    ("lexicon", "Balarri was admitted as queenfish only; older narrative/action contexts did not license catching, eating, water, or event rows.", "Rule 240: balarri."),
    ("lexicon", "Bilmbin was admitted as black-tip shark only; black-tip ray alternate, river/mangrove habitat prose, danger, and bite rows stayed closed.", "Rule 240: bilmbin."),
    ("lexicon", "Jalkay was admitted as salmon only in new perception frames; earlier bare-deictic rows did not license catching, water, food, or event rows.", "Rule 240: jalkay."),
    ("lexicon", "Jijirr was admitted as red bream only; colour-predicate, reef/habitat, catching, and food prose stayed closed.", "Rule 240: jijirr."),
    ("morphology", "All Rule 240 target nouns stayed bare: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or target suffix was admitted.", "Rule 240: bare targets."),
    ("morphology", "The subject support forms stayed bare nominatives: no pronoun case forms, possessive readings, or person/number extensions were introduced.", "Rule 240: bare nominative pronouns."),
    ("morphology", "Yaluy, yinyay, and nyajil stayed uninflected support heads; no demonstrative case, local-derived form, verb nominalization, purposive, or support suffix was admitted.", "Rule 240: uninflected support."),
    ("morphology", "No target compound, lexicalized trap compound, or productive reduplication was built from the fish heads.", "Rule 240: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngayu TARGET yinyay nyajil.", "Rule 240: 1sg there perception band."),
    ("syntax", "Rows 11-20 used Nyulu TARGET yaluy nyajil.", "Rule 240: 3sg here perception band."),
    ("syntax", "Rows 21-30 used Yurra TARGET yinyay nyajil.", "Rule 240: 2pl there perception band."),
    ("syntax", "Rows 31-40 used Bula TARGET yaluy nyajil.", "Rule 240: 3du here perception band."),
    ("syntax", "Rows 41-50 used Jana TARGET yinyay nyajil.", "Rule 240: 3pl there perception band."),
    ("fidelity", "English stayed literal perception/reference prose: subject pronoun, selected fish label, here/there, and see only.", "Rule 240: literal English."),
    ("fidelity", "The batch did not convert dictionary examples or source prose into catching, netting, hook/line, spearing, eating, cooking, bait, taboo, storm/thunder, story/place, water/river/sea/reef/habitat, body-part, colour, danger, or injury claims.", "Rule 240: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style perception clauses; no fishing instruction, food preparation, taboo, story-site, ecology, danger, or narrative register was introduced.", "Rule 240: register."),
    ("process", "Rules 149-239 carry-forward traps stayed closed, especially fish-use/action traps, flora/fauna use or event rows, body-part possession/case/perception drift, dwelling action/use/source traps, and fire action/use/homograph traps.", "Rule 240: carry-forward closure."),
    ("handoff", "Next batch may continue from 14,197 if this closes; do not infer catching, eating, fishing gear, water/habitat, story, danger, colour predicate, target case, pronoun case, perception-compound, or support-inflection grammar from Rule 240.", "Rule 240: next cadence."),
]

LEXEMES = [
    ("kubija", "noun", None, "NA", "barracuda", "batch-282: barracuda perception/reference only; garfish alternate and fishing/water/habitat prose closed."),
    ("mujarrka", "noun", None, "NA", "archerfish", "batch-282: archerfish perception/reference only; Yalanji label retained, spotted-Jewfish/Nyungkul/habitat prose closed."),
    ("barrbal", "noun", None, "NA", "black bream", "batch-282: black-bream perception/reference only; catching, eating, water, reef/habitat, colour, and event prose closed."),
    ("wuyumbu", "noun", None, "NA", "toadfish", "batch-282: toadfish perception/reference only; striped-toby/generic-fish prose closed."),
    ("bayil", "noun", None, "NA", "perch", "batch-282: perch perception/reference only; jungle/freshwater and catch/eat/habitat prose closed."),
    ("dalmbal", "noun", None, "NA", "flathead", "batch-282: flathead perception/reference only; dukul-barangka synonym and compound/action/use prose closed."),
    ("balarri", "noun", None, "NA", "queenfish", "batch-282: queenfish perception/reference only; no catching, eating, water, or event row."),
    ("bilmbin", "noun", None, "NA", "black-tip shark", "batch-282: black-tip shark perception/reference only; black-tip ray, habitat, danger, and bite prose closed."),
    ("jalkay", "noun", None, "NA", "salmon", "batch-282: salmon perception/reference only; no catching, water, food, or event row."),
    ("jijirr", "noun", None, "NA", "red bream", "batch-282: red-bream perception/reference only; colour-predicate, reef/habitat, catch, and food prose closed."),
    ("ngayu", "pronoun", None, "NA", "first singular nominative", "batch-282: bare nominative subject support only."),
    ("nyulu", "pronoun", None, "NA", "third singular nominative", "batch-282: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-282: bare nominative subject support only."),
    ("bula", "pronoun", None, "NA", "third dual nominative", "batch-282: bare nominative subject support only."),
    ("jana", "pronoun", None, "NA", "third plural nominative", "batch-282: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-282: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-282: bare local demonstrative support only."),
    ("nyajil", "verb", "l", "NA", "see", "batch-282: nonpast perception support only."),
]


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:
        raise SystemExit(f"{LABEL} must have 50 rows before close; found {total}")
    if accepted:
        raise SystemExit(f"{LABEL} already has {accepted} accepted/revised rows; refusing to overwrite")
    if under_review != 50:
        raise SystemExit(f"{LABEL} must have 50 under_review rows before close; found {under_review}")

    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-282-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 240 rows. Morphology checked bare fish nouns, bare nominative pronouns, bare yaluy/yinyay, and nyajil nonpast only. Lexicon checked selected fish labels only. Syntax checked five pronoun-perception frame bands. Fidelity checked literal 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 bayilbayil unhyphenated reduplication, no kijukum illegal-coda form, no ngiwa sea-snake/place/story-site homograph, no yidilnyul Nyungkul-only manta form, no walarrji rhotic-palatal-lint drift, no catching/netting/hook-line/spearing action, no eating/cooking/food/bait use, no taboo/storm/thunder/story/place/water/river/sea/reef/habitat prose, no fish body-part analysis, no colour predicate, no target case, no productive compound, no productive reduplication, no pronoun case, no perception compound, and no 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 240 lessons covering source checks, lexical target senses, hard exclusions, morphology, syntax, fidelity, register, process traps, and handoff.",
        artifact_path="batch_scripts/close_282.py",
        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 240 targets and support heads.",
        artifact_path="batch_scripts/close_282.py",
        created_at=NOW,
    )
    db.execute("UPDATE batches SET notes=? WHERE id=?", (NOTES, batch_id))
    db.execute("UPDATE sentences SET status='accepted', updated_at=? WHERE batch_id=?", (NOW, batch_id))
    record_event(
        db,
        batch_label=LABEL,
        phase="close",
        event_type="close-success",
        actor="claude-main",
        detail="Closed Batch 282: 50 accepted Rule 240 fish-reference perception rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_282.py",
        artifact_path="batch_scripts/close_282.py",
        created_at=NOW,
    )
    db.commit()

    reviews = db.execute(
        "SELECT COUNT(*) FROM reviews WHERE sentence_id IN (SELECT id FROM sentences WHERE batch_id=?)",
        (batch_id,),
    ).fetchone()[0]
    lessons = 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-282-verify'"
    ).fetchone()[0]
    verified_after, words_after = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    print(
        f"closed {LABEL}: accepted=50, reviews={reviews}, lessons={lessons}, "
        f"lexeme_logs={lexeme_logs}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before}->{words_after}"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
