#!/usr/bin/env python3
"""Close batch-258 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-258"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-258-low-frequency-food-reference-lexical-expansion-after-rule215-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "LOW-FREQUENCY FOOD-REFERENCE LEXICAL EXPANSION AFTER RULE 215 (Rule 216). 50 rows. TARGETS: "
    "birukay yolk, biyangkal yam, darka nut, dukal fig, jadamu bananas, jamal egg white, jungu-jungu white ant eggs, "
    "mujurr witchetty grub, wawukuna long wild yam, and wuynkurr meat juice. SUPPORT: uninflected yinya/yaluy/yinyay. "
    "FRAMES: TARGET yaluy, TARGET yinyay, Yinya TARGET yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. REVIEW: "
    "all target nouns stayed bare reference labels. No target case, possession, comitative, instrumental, locative, "
    "number morphology, derivation, productive compound, productive reduplication, cooking, roasting, grinding, "
    "leaching, eating, edible-use, medicine, sickness, alcohol, loan, gathering, collecting, habitat, water/fire, "
    "meat-source, support inflection, or Rule 215 person-quality drift was opened."
)

LESSONS = [
    ("process", "Rule 216 selected food-reference only after a fresh source pass and kept all food preparation/use semantics closed.", "Rule 216: food-reference cadence."),
    ("source", "Patz section 3.1 treats nouns as nominals that refer to objects; food nouns can be referenced in bare nominal frames.", "Rule 216: noun source."),
    ("source", "Patz section 3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'; Rule 216 keeps all three uninflected.", "Rule 216: demonstrative source."),
    ("process", "Prior reference-batch wording from Rules 212-213 was reused for the five deictic frame bands.", "Rule 216: reference wording."),
    ("process", "Banabul, mayngku, and jarru were rejected as loan/post-contact heads for this batch.", "Rule 216: loan rejection."),
    ("process", "Kalbal and kamu-kamu were rejected for medicine/sickness and alcohol pressure; damba, balja, and jandu were rejected for heavier preparation or post-contact pressure.", "Rule 216: unsafe food rejections."),
    ("lexicon", "Birukay stayed yolk reference only; egg collecting, cooking, eating, and body/source expansion stayed closed.", "Rule 216: birukay."),
    ("lexicon", "Biyangkal stayed yam reference only; roasting, grinding, leaching, safety, and eating prose stayed closed.", "Rule 216: biyangkal."),
    ("lexicon", "Darka stayed nut reference only; tree/source, eating, gathering, and preparation prose stayed closed.", "Rule 216: darka."),
    ("lexicon", "Dukal stayed fig reference only; fruit/edible/roasting and tree/ecology readings stayed closed.", "Rule 216: dukal."),
    ("lexicon", "Jadamu stayed bananas reference only; plant/cultivation/eating and loan-drift readings stayed closed.", "Rule 216: jadamu."),
    ("lexicon", "Jamal stayed egg-white reference only; albumen/egg collection/cooking/eating expansions stayed closed.", "Rule 216: jamal."),
    ("lexicon", "Jungu-jungu stayed white-ant-eggs reference only; insect behavior, gathering, nest, and food-use events stayed closed.", "Rule 216: jungu-jungu."),
    ("lexicon", "Mujurr stayed witchetty-grub reference only; rotting-wood habitat, collecting, edible, and insect-event prose stayed closed.", "Rule 216: mujurr."),
    ("lexicon", "Wawukuna stayed long-wild-yam reference only; digging, cooking, eating, and plant-use prose stayed closed.", "Rule 216: wawukuna."),
    ("lexicon", "Wuynkurr stayed meat-juice reference only; fat/source, cooking, eating, and meat-use prose stayed closed.", "Rule 216: wuynkurr."),
    ("morphology", "All target food nouns stayed bare: no target case, possession, comitative, instrumental, locative, number, derivation, or suffixing.", "Rule 216: bare nouns."),
    ("morphology", "Lexicalized jungu-jungu was admitted only as a dictionary headword; no productive reduplication was opened.", "Rule 216: reduplication guard."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support forms only.", "Rule 216: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 216: TARGET here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 216: TARGET there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 216: demonstrative TARGET there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 216: TARGET demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 216: demonstrative TARGET here frame."),
    ("fidelity", "English stayed literal reference prose: target noun plus here/there/that support.", "Rule 216: literal English."),
    ("fidelity", "Plural English was used only where the dictionary target is plural: jadamu bananas and jungu-jungu white ant eggs.", "Rule 216: plural fidelity."),
    ("register", "Rows remained plain elicitation-style reference statements, not recipes, harvesting notes, medical claims, or food-use narratives.", "Rule 216: register."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, and live docs are required evidence before treating Rule 216 as complete.", "Rule 216: evidence standard."),
    ("handoff", "Next batch may continue from 12,997 if this closes; do not infer food preparation, eating, medicine, gathering, habitat, or morphology from Rule 216.", "Rule 216: next cadence."),
]

LEXEMES = [
    ("birukay", "noun", None, "NA", "yolk", "batch-258: yolk reference only; egg collection/cooking/eating closed."),
    ("biyangkal", "noun", None, "NA", "yam", "batch-258: yam reference only; roasting/grinding/leaching/eating prose closed."),
    ("darka", "noun", None, "NA", "nut", "batch-258: nut reference only; tree/source/eating/gathering closed."),
    ("dukal", "noun", None, "NA", "fig", "batch-258: fig reference only; edible/roasting/tree ecology closed."),
    ("jadamu", "noun", None, "NA", "bananas", "batch-258: bananas reference only; plant/cultivation/eating closed."),
    ("jamal", "noun", None, "NA", "egg white", "batch-258: egg-white reference only; egg collection/cooking/eating closed."),
    ("jungu-jungu", "noun", None, "NA", "white ant eggs", "batch-258: white-ant-eggs reference only; gathering/insect/nest/event readings closed."),
    ("mujurr", "noun", None, "NA", "witchetty grub", "batch-258: witchetty-grub reference only; rotting-wood habitat/collecting/edible readings closed."),
    ("wawukuna", "noun", None, "NA", "long wild yam", "batch-258: long-wild-yam reference only; digging/cooking/eating/plant-use closed."),
    ("wuynkurr", "noun", None, "NA", "meat juice", "batch-258: meat-juice reference only; fat/source/cooking/eating closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-258: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-258: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-258: distal demonstrative support only; no inflection."),
]


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.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-258-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 216 rows. Morphology checked bare food nouns and uninflected yinya/yaluy/yinyay support. Lexicon checked selected food-reference senses only. Syntax checked five deictic reference frames. Fidelity checked literal reference English. Register stayed plain reference statement.",
        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 target case, possession, comitative, instrumental, locative, number morphology, derivation, productive compounding, productive reduplication, cooking, roasting, grinding, leaching, eating, edible-use, medicine, sickness, alcohol, loan, gathering, collecting, habitat, water/fire, meat-source, support inflection, or Rule 215 drift.",
        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 216 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_258.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 216 targets and support heads.",
        artifact_path="batch_scripts/close_258.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 258: 50 accepted Rule 216 low-frequency food-reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_258.py",
        artifact_path="batch_scripts/close_258.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]
    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}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before or 0}->{words_after or 0}"
    )
    return 0


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