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

NOTES = (
    "LOW-COVERAGE TREE REFERENCE LEXICAL EXPANSION AFTER RULE 207 (Rule 208). 50 rows. TARGETS: banday "
    "cherry-like tree, bijan ti tree, bukunjarra bukunjarra tree, bulngkarr lady apple tree, wanakan wanakan tree, "
    "warka messmate tree, wulngkurr stringybark tree, yalngkal white wattle, yarun black wattle, and yumba wattle tree. "
    "FRAMES: TARGET yaluy, TARGET yinyay, Yinya TARGET yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. REVIEW: "
    "all target nouns stayed bare absolutive reference heads; yinya/yaluy/yinyay stayed uninflected support only; "
    "English stayed literal here/there/that reference prose. No target case, possession, comitative, instrumental, "
    "locative, derivation, number, compound, fruit/edible/food/seed/nut/flower/season, medicine, bark, wood, timber, "
    "source/material/use, burning, cooking, roasting, leaching, gathering, ecology, place/story/country, ownership, "
    "ceremony/magic/death, homograph, or support-inflection drift was opened."
)

LESSONS = [
    ("process", "Rule 208 used a new tree-reference lexical field after Rule 207 object references.", "Rule 208: tree-reference cadence."),
    ("source", "Patz §3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'.", "Rule 208: demonstrative source."),
    ("source", "Patz §3.7 permits yinya before or after a noun; Rule 208 kept both positions but no inflected demonstrative forms.", "Rule 208: yinya position."),
    ("process", "Older tree heads with accepted simple-deictic collisions were deferred instead of reused.", "Rule 208: duplicate restraint."),
    ("process", "The misspelled candidate bugunjara was rejected; only source-backed bukunjarra was admitted.", "Rule 208: phantom rejection."),
    ("lexicon", "Banday stayed cherry-like tree only; fruit, ripening, food, and season details stayed closed.", "Rule 208: banday."),
    ("lexicon", "Bijan stayed ti tree only; bark, roofing, painting, and material-use readings stayed closed.", "Rule 208: bijan."),
    ("lexicon", "Bukunjarra stayed tree-reference only; edible fruit and food readings stayed closed.", "Rule 208: bukunjarra."),
    ("lexicon", "Bulngkarr stayed lady apple tree only; fruit and eating readings stayed closed.", "Rule 208: bulngkarr."),
    ("lexicon", "Wanakan stayed tree-reference only; fruit, ripening, roasting, food, and season details stayed closed.", "Rule 208: wanakan."),
    ("lexicon", "Warka stayed messmate tree only; stringybark/material/source readings stayed closed.", "Rule 208: warka."),
    ("lexicon", "Wulngkurr stayed stringybark tree only; bark/material/source readings stayed closed.", "Rule 208: wulngkurr."),
    ("lexicon", "Yalngkal stayed white wattle only; flower/material/use readings stayed closed.", "Rule 208: yalngkal."),
    ("lexicon", "Yarun stayed black wattle only; yellow-flower and use readings stayed closed.", "Rule 208: yarun."),
    ("lexicon", "Yumba stayed wattle tree only; wood/material/use readings stayed closed.", "Rule 208: yumba."),
    ("morphology", "All target tree nouns stayed bare: no case, possession, comitative, instrumental, locative, plural, derivation, compound, or reduplication.", "Rule 208: bare nouns."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected; no demonstrative case, possessive, comitative, or local-derived forms were opened.", "Rule 208: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 208: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 208: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 208: initial demonstrative there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 208: postposed demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 208: initial demonstrative here frame."),
    ("fidelity", "English stayed literal: selected tree label plus here/there/that support only.", "Rule 208: literal English."),
    ("fidelity", "No English plant-use, source, material, food, medicine, ecology, place, story, ownership, or event wording was imported.", "Rule 208: denied English fields."),
    ("register", "Rows remained plain reference/location sentences, not ecological descriptions, harvesting/cooking/eating reports, plant-use instructions, or place stories.", "Rule 208: register."),
    ("handoff", "Next batch may continue from 12,597 if this closes; do not infer plant-use, source, ecology, story, target morphology, or support inflection from Rule 208.", "Rule 208: next cadence."),
]

LEXEMES = [
    ("banday", "noun", None, "NA", "cherry-like tree", "batch-250: cherry-like tree noun only; fruit/ripening/food/season closed."),
    ("bijan", "noun", None, "NA", "ti tree", "batch-250: ti tree noun only; bark/roofing/painting/material-use closed."),
    ("bukunjarra", "noun", None, "NA", "bukunjarra tree", "batch-250: tree noun only; edible fruit/food readings closed."),
    ("bulngkarr", "noun", None, "NA", "lady apple tree", "batch-250: lady apple tree noun only; fruit/eating readings closed."),
    ("wanakan", "noun", None, "NA", "wanakan tree", "batch-250: tree noun only; fruit/ripening/roasting/food/season closed."),
    ("warka", "noun", None, "NA", "messmate tree", "batch-250: messmate tree noun only; bark/material/source readings closed."),
    ("wulngkurr", "noun", None, "NA", "stringybark tree", "batch-250: stringybark tree noun only; bark/material/source readings closed."),
    ("yalngkal", "noun", None, "NA", "white wattle", "batch-250: white wattle noun only; flower/material/use readings closed."),
    ("yarun", "noun", None, "NA", "black wattle", "batch-250: black wattle noun only; flower/material/use readings closed."),
    ("yumba", "noun", None, "NA", "wattle tree", "batch-250: wattle tree noun only; wood/material/use readings closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-250: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-250: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-250: distal demonstrative support only, before or after noun; 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-250-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 by SQL token estimate)",
        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 208 rows. Morphology checked bare tree targets and uninflected yinya/yaluy/yinyay. Lexicon checked selected tree labels only. Syntax checked five deictic/reference frames. Fidelity checked literal here/there/that English. Register stayed plain reference/location.",
        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, plural, derivation, compound, productive reduplication, fruit/edible/food/seed/nut/flower/season, medicine, bark, wood, timber, source/material/use, burning, cooking, roasting, leaching, gathering, ecology, place/story/country, ownership, ceremony/magic/death, yala/yanyu, 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 208 lessons covering source checks, candidate rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_250.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 208 targets and demonstrative heads.",
        artifact_path="batch_scripts/close_250.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 250: 50 accepted Rule 208 low-coverage tree reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_250.py",
        artifact_path="batch_scripts/close_250.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())
