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

NOTES = (
    "FIRE-REFERENCE LEXICAL EXPANSION AFTER RULE 235 (Rule 236). 50 rows. "
    "TARGETS: baya fire, jimal fire stick, jirramar small sticks, kubu smoke, kunjin fire, miyilkura smouldering log, "
    "ngalku bush fire, ngaluri flames, ngunjil charcoal, and wula flames. 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 fire-domain reference labels. No fire-making, lighting, collecting, cooking, "
    "burning, clearing, spreading, leaping-flame event, hot-coal/ash extension, firewood use, loan, body-fluid homograph, "
    "target case, target compound, productive reduplication, or support inflection was opened."
)

LESSONS = [
    ("source", "Patz section 3.1 supports nouns as terms for objects, weather phenomena, artefacts, and other objects of human habitat; Rule 236 uses that nominal source for fire-domain nouns only.", "Rule 236: nominal source."),
    ("source", "Patz section 3.7 sources yinya 'that/those', yaluy 'here', and yinyay 'there'; Rule 236 keeps all support heads bare and uninflected.", "Rule 236: demonstrative source."),
    ("process", "Exact duplicate preflight over all 50 planned Rule 236 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 236: duplicate preflight."),
    ("process", "Pre-batch coverage showed four genuinely absent targets: jirramar, miyilkura, ngalku, and ngaluri had 0 accepted/revised token hits.", "Rule 236: coverage audit."),
    ("lexicon", "Baya is admitted as fire reference only; firewood, lighting, collecting, and cooking prose remain closed.", "Rule 236: baya."),
    ("lexicon", "Jimal is admitted as fire-stick reference only; jimal damal fire-making and jimalili story prose remain closed.", "Rule 236: jimal."),
    ("lexicon", "Jirramar is admitted as small-sticks reference only; starting-fire/kindling-use prose remains closed.", "Rule 236: jirramar."),
    ("lexicon", "Kubu is admitted as smoke reference only; source/from-smoke movement and fire-event prose remain closed.", "Rule 236: kubu."),
    ("lexicon", "Kunjin is admitted as fire reference only; no new contrast with baya is asserted beyond dictionary synonymy.", "Rule 236: kunjin."),
    ("lexicon", "Miyilkura is admitted as smouldering-log reference only; no burning, cooking, or fire-management event is opened.", "Rule 236: miyilkura."),
    ("lexicon", "Ngalku is admitted as bush-fire reference only; spreading, clearing, grassfire, danger, or burn-event rows remain closed.", "Rule 236: ngalku."),
    ("lexicon", "Ngaluri is admitted as flames reference only; the source usage with flames leaping up is not converted into an event row.", "Rule 236: ngaluri."),
    ("lexicon", "Ngunjil is admitted as charcoal reference only; hot coals and hot ashes extensions remain closed.", "Rule 236: ngunjil."),
    ("lexicon", "Wula is admitted as flames reference only; dalngarri synonymy and dalngarri's urine/body-fluid homograph remain closed.", "Rule 236: wula."),
    ("morphology", "All Rule 236 target nouns stayed bare: no target LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or suffixing.", "Rule 236: bare targets."),
    ("morphology", "Jirramar, ngaluri, and wula have plural English readings only; no Kuku number morphology was introduced.", "Rule 236: lexical plural."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads; no demonstrative case, possessive, comitative, local-derived, plural-human, proximal, or support-inflection form was opened.", "Rule 236: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 236: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 236: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 236: preposed that-there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 236: postposed that-there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 236: preposed that-here frame."),
    ("fidelity", "English stayed literal fire-reference prose: selected fire-domain label plus here/there/that only.", "Rule 236: literal English."),
    ("fidelity", "The batch did not convert dictionary definitions into fire-making, lighting, collecting, cooking, burning, clearing, spreading, smoke-source, hot-coal, ash, body-fluid, or story claims.", "Rule 236: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements; no ceremonial, danger, story, or instruction register was introduced.", "Rule 236: register."),
    ("process", "Rules 149-235 carry-forward traps stayed closed, especially recent body-part possession/case/perception-compound drift and landform route/water/event drift.", "Rule 236: carry-forward closure."),
    ("handoff", "Next batch may continue from 13,997 if this closes; do not infer fire-making, cooking, burning, clearing, spreading, hot-coal/ash, body-fluid homograph, loan, target-case, or support-inflection grammar from Rule 236.", "Rule 236: next cadence."),
]

LEXEMES = [
    ("baya", "noun", None, "NA", "fire", "batch-278: fire reference only; no firewood, lighting, collecting, or cooking row."),
    ("jimal", "noun", None, "NA", "fire stick", "batch-278: fire-stick reference only; no fire-making row."),
    ("jirramar", "noun", None, "NA", "small sticks", "batch-278: small-sticks reference only; no starting-fire use row."),
    ("kubu", "noun", None, "NA", "smoke", "batch-278: smoke reference only; no source/event row."),
    ("kunjin", "noun", None, "NA", "fire", "batch-278: fire reference only."),
    ("miyilkura", "noun", None, "NA", "smouldering log", "batch-278: smouldering-log reference only; no burning/cooking row."),
    ("ngalku", "noun", None, "NA", "bush fire", "batch-278: bush-fire reference only; no spreading/clearing/danger row."),
    ("ngaluri", "noun", None, "NA", "flames", "batch-278: flames reference only; no leaping-flames event row."),
    ("ngunjil", "noun", None, "NA", "charcoal", "batch-278: charcoal reference only; hot coals/ashes remain closed."),
    ("wula", "noun", None, "NA", "flames", "batch-278: flames reference only; dalngarri/body-fluid homograph closed."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-278: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-278: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-278: local demonstrative 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.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-278-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 236 rows. Morphology checked bare fire-domain nouns, lexical/contextual plural English only for jirramar/ngaluri/wula, uninflected support heads, and no target case. Lexicon checked selected fire-reference senses only. Syntax checked five deictic/demonstrative bands. Fidelity checked literal fire-reference 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 firewood row, no lighting or fire-making row, no collecting or cooking row, no burning/clearing/spreading event row, no leaping-flame event row, no hot-coal/ash extension, no dalngarri urine or nulung pus homograph, no loan, no recent body-part/landform drift, no target case, no productive compound, no productive reduplication, 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 236 lessons covering source checks, coverage audit, lexical target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_278.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 236 targets and support heads.",
        artifact_path="batch_scripts/close_278.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 278: 50 accepted Rule 236 fire-reference lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_278.py",
        artifact_path="batch_scripts/close_278.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}->{words_after}"
    )
    return 0


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