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

NOTES = (
    "DWELLING AND HOUSEHOLD REFERENCE EXPANSION AFTER RULE 237 (Rule 238). 50 rows. "
    "TARGETS: bakarr ridge pole, bayan house, bira windbreak, jiji roof, kilili windbreak, wurun humpy, "
    "jakway door, yulal board, kararr blanket, and bilangkurr blanket. SUPPORT: yinya/yaluy/yinyay plus "
    "bare nyulu and nyajil. FRAMES: Yinya TARGET yaluy, Yinya TARGET yinyay, TARGET yinya yaluy, "
    "TARGET yinya yinyay, and Nyulu TARGET yinyay nyajil. REVIEW: no yamba/opium/particle/none homograph, "
    "jakal mouse/full/front homograph, warrbi axe/beehive-house homograph, building/setting/spreading/entering/"
    "nailing action, roofing/source-material prose, sleeping/covering/warming use, front/open/shut extension, "
    "plank/round-stick contrast, top-of-anything extension, target case, target compound, productive reduplication, "
    "pronoun case, perception compound, support inflection, or recent fire/body drift was opened."
)

LESSONS = [
    ("source", "Rule 238 admitted ten checked noun heads from dictionary or grammar-added dictionary entries: bakarr, bayan, bira, jiji, kilili, wurun, jakway, yulal, kararr, and bilangkurr.", "Rule 238: target inventory."),
    ("source", "Patz section 3.1.2 supports nouns as terms for artifacts and objects of human habitat, and explicitly lists bayan as camp/house/shelter.", "Rule 238: noun source."),
    ("source", "Patz section 3.7 supplies yinya, yaluy, yinyay and states that with one noun a demonstrative may precede or follow the noun.", "Rule 238: demonstrative source."),
    ("source", "Patz section 3.5 supplies bare nominative nyulu; Patz section 3.8.3.2 supplies nyaji-l 'see'. Rule 238 does not open pronoun case or perception compounds.", "Rule 238: perception source."),
    ("process", "Exact duplicate preflight over all 50 planned Rule 238 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 238: duplicate preflight."),
    ("process", "Token-boundary coverage before banking was bakarr 0, bayan 437, bira 1, jiji 0, kilili 0, wurun 23, jakway 10, yulal 10, kararr 17, and bilangkurr 17.", "Rule 238: coverage audit."),
    ("lexicon", "Bakarr was admitted as ridge pole only; pole/material/source/building prose stayed closed.", "Rule 238: bakarr."),
    ("lexicon", "Bayan was admitted as house only in the English rows; camp/shelter synonymy is acknowledged in notes but no camping, building, possession, or locative house row was opened.", "Rule 238: bayan."),
    ("lexicon", "Bira was admitted as windbreak only; making, setting, rain, weather, or material-source prose stayed closed.", "Rule 238: bira."),
    ("lexicon", "Jiji was admitted as roof only; top-of-anything extension and roofing-material prose stayed closed.", "Rule 238: jiji."),
    ("lexicon", "Kilili was admitted as windbreak only; no construction, weather, or material-source row was opened.", "Rule 238: kilili."),
    ("lexicon", "Wurun was admitted as humpy only; halfway translation, locative humpy rows, building, sleeping, and rain-shelter event prose stayed closed.", "Rule 238: wurun."),
    ("lexicon", "Jakway was admitted as door only; front sense, opening, closing, shutting, and jakal homograph material stayed closed.", "Rule 238: jakway."),
    ("lexicon", "Yulal was admitted as board only; plank wording, round-stick contrast, nailing, building, and source-material prose stayed closed.", "Rule 238: yulal."),
    ("lexicon", "Kararr was admitted as blanket only; sheet, grass bedding, spreading, sleeping, covering, warming, and year-counting extensions stayed closed.", "Rule 238: kararr."),
    ("lexicon", "Bilangkurr was admitted as blanket only; clothing, sleeping, covering, warming, and ownership rows stayed closed.", "Rule 238: bilangkurr."),
    ("morphology", "All Rule 238 target nouns stayed bare: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or target suffix was admitted.", "Rule 238: bare targets."),
    ("morphology", "The lexicalized reduplication/trap forms yamba-yamba and productive reduplication were not used; no target compound was built.", "Rule 238: no productive reduplication."),
    ("morphology", "Yinya, yaluy, yinyay, nyulu, and nyajil stayed bare support heads; no demonstrative case, local-derived form, pronoun case, or support inflection was admitted.", "Rule 238: uninflected support."),
    ("syntax", "Rows 1-10 used Yinya TARGET yaluy.", "Rule 238: preposed demonstrative here band."),
    ("syntax", "Rows 11-20 used Yinya TARGET yinyay.", "Rule 238: preposed demonstrative there band."),
    ("syntax", "Rows 21-30 used TARGET yinya yaluy.", "Rule 238: postposed demonstrative here band."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 238: postposed demonstrative there band."),
    ("syntax", "Rows 41-50 used Nyulu TARGET yinyay nyajil.", "Rule 238: 3sg nonpast perception band."),
    ("fidelity", "English stayed literal reference/perception prose: selected target label plus here/there/that/see only.", "Rule 238: literal English."),
    ("fidelity", "The batch did not convert dictionary examples or source prose into building, setting up camp, spreading blankets, sleeping, covering, warming, entering, nailing, roofing, or weather-shelter claims.", "Rule 238: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference/perception clauses; no ceremonial, mortuary, property, ownership, instruction, storm-preparation, or household-use register was introduced.", "Rule 238: register."),
    ("process", "Rules 149-237 carry-forward traps stayed closed, especially recent fire action/use/homograph traps, body-part possession/case/perception drift, and landform route/water/event drift.", "Rule 238: carry-forward closure."),
    ("handoff", "Next batch may continue from 14,097 if this closes; do not infer shelter-building, camp setup, blanket use, door action, board nailing, source-material, ownership, target case, pronoun case, perception-compound, or support-inflection grammar from Rule 238.", "Rule 238: next cadence."),
]

LEXEMES = [
    ("bakarr", "noun", None, "NA", "ridge pole", "batch-280: dwelling/household reference only; ridge-pole reference/perception, no building or material-source row."),
    ("bayan", "noun", None, "NA", "house", "batch-280: house reference/perception only; no camping, building, possession, or locative house row."),
    ("bira", "noun", None, "NA", "windbreak", "batch-280: windbreak reference/perception only; no making, setting, weather, or material-source row."),
    ("jiji", "noun", None, "NA", "roof", "batch-280: roof reference/perception only; top-of-anything and roofing-material extensions closed."),
    ("kilili", "noun", None, "NA", "windbreak", "batch-280: windbreak reference/perception only; no construction/weather/source row."),
    ("wurun", "noun", None, "NA", "humpy", "batch-280: humpy reference/perception only; no halfway, building, sleeping, rain-shelter, or locative row."),
    ("jakway", "noun", None, "NA", "door", "batch-280: door reference/perception only; front/open/close/shut and jakal homograph closed."),
    ("yulal", "noun", None, "NA", "board", "batch-280: board reference/perception only; plank, round-stick contrast, nailing, and building prose closed."),
    ("kararr", "noun", None, "NA", "blanket", "batch-280: blanket reference/perception only; sheet/grass bedding/spread/sleep/cover/warm/year-count extensions closed."),
    ("bilangkurr", "noun", None, "NA", "blanket", "batch-280: blanket reference/perception only; clothing/sleep/cover/warm/ownership rows closed."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-280: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-280: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-280: local demonstrative support only."),
    ("nyulu", "pronoun", None, "NA", "third singular", "batch-280: bare nominative support only."),
    ("nyajil", "verb", "l", "NA", "see", "batch-280: 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.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-280-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 238 rows. Morphology checked bare dwelling/household nouns, bare yinya/yaluy/yinyay/nyulu/nyajil support, and no target case. Lexicon checked selected target senses only. Syntax checked five 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 yamba/opium/particle/none homograph, no jakal mouse/full/front homograph, no warrbi axe/beehive-house homograph, no building/setting/spreading/entering/nailing action, no roofing/source-material prose, no sleeping/covering/warming use, no front/open/shut extension, no plank/round-stick contrast, no top-of-anything extension, no target case, no productive compound, no productive reduplication, no pronoun case, no perception compound, no support inflection, and no recent fire/body 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 238 lessons covering source checks, lexical target senses, morphology, syntax, fidelity, register, process traps, and handoff.",
        artifact_path="batch_scripts/close_280.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 238 targets and support heads.",
        artifact_path="batch_scripts/close_280.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 280: 50 accepted Rule 238 dwelling and household reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_280.py",
        artifact_path="batch_scripts/close_280.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())
