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

NOTES = (
    "LOW-COVERAGE NAMED TREE-REFERENCE LEXICAL EXPANSION AFTER RULE 223 (Rule 224). 50 rows. TARGETS: "
    "jundul jundul tree, kabariji cherry tree, kawunjil black cherry tree, kayjurr white gum, kingal river oak, "
    "kulbar white beech, kumin kumin fig tree, marbaji stringybark tree, milbanku pencil cedar, and mujarr mujarr fig tree. "
    "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 named-tree-reference labels. "
    "No earlier tree/flora target reopening, place-heavy candidate, exact-collision candidate, fruit/food/seed/poison/"
    "leaching row, medicine row, bark-use row, timber/material-source row, ecology/habitat row, place/story/country row, "
    "ownership row, target case, number morphology, derivation, productive compounding, productive reduplication, or support inflection was opened."
)

LESSONS = [
    ("process", "Rule 224 continued lexical coverage only after checking earlier tree/flora target sets for exact surface collisions and semantic carry-forward traps.", "Rule 224: named tree cadence."),
    ("source", "Patz section 3.1 supports flora nouns as nominal referents; Rule 224 uses bare named-tree nouns only.", "Rule 224: flora noun source."),
    ("source", "Patz section 3.7 supports yinya, yaluy, and yinyay; Rule 224 keeps all three uninflected.", "Rule 224: demonstrative source."),
    ("process", "Rule 224 reused bare deictic reference frames because they add lexical coverage without importing plant-use, food, material-source, habitat, or place grammar.", "Rule 224: reference wording."),
    ("process", "Rejected or deferred fields included previous tree/flora target heads, place-heavy candidates, exact-collision candidates, food/fruit/seed/poison/leaching prose, medicine, bark-use, timber/material-source, ecology, place/story/country, and ownership semantics.", "Rule 224: rejected tree fields."),
    ("lexicon", "Jundul stayed jundul-tree reference only; poisonous/leaching wild-plum prose stayed closed.", "Rule 224: jundul."),
    ("lexicon", "Kabariji stayed cherry-tree reference only; fruit and food prose stayed closed.", "Rule 224: kabariji."),
    ("lexicon", "Kawunjil stayed black-cherry-tree reference only; fruit, sweetness, ripening, and wet-season prose stayed closed.", "Rule 224: kawunjil."),
    ("lexicon", "Kayjurr stayed white-gum reference only.", "Rule 224: kayjurr."),
    ("lexicon", "Kingal stayed river-oak reference only; beach and habitat prose stayed closed.", "Rule 224: kingal."),
    ("lexicon", "Kulbar stayed white-beech reference only; timber and material prose stayed closed.", "Rule 224: kulbar."),
    ("lexicon", "Kumin stayed kumin-fig-tree reference only; edible-fruit and season prose stayed closed.", "Rule 224: kumin."),
    ("lexicon", "Marbaji stayed stringybark-tree reference only.", "Rule 224: marbaji."),
    ("lexicon", "Milbanku stayed pencil-cedar reference only; edible seed-skin prose stayed closed.", "Rule 224: milbanku."),
    ("lexicon", "Mujarr stayed mujarr-fig-tree reference only; edible fruit, trunk, colour, and season prose stayed closed.", "Rule 224: mujarr."),
    ("morphology", "All target named-tree nouns stayed bare: no target case, possession, comitative, instrumental, locative, number, derivation, suffixing, plural, or reduplication.", "Rule 224: bare nouns."),
    ("morphology", "English modifiers inside labels, such as black, white, river, pencil, stringybark, and fig, remained lexical labels rather than Kuku morphology or separate predicates.", "Rule 224: label morphology guard."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support forms only.", "Rule 224: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 224: TARGET here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 224: TARGET there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 224: demonstrative TARGET there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 224: TARGET demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 224: demonstrative TARGET here frame."),
    ("fidelity", "English stayed literal reference prose: target named-tree label plus here/there/that support.", "Rule 224: literal English."),
    ("fidelity", "The batch did not turn source definitions into fruit, edible, food, poison, leaching, medicine, bark-use, timber, material-source, ecology, place, story, country, ownership, habitat, or season claims.", "Rule 224: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements, not plant-use statements, food statements, material-source reports, habitat descriptions, place-name claims, or seasonal ecology claims.", "Rule 224: 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 224 as complete.", "Rule 224: evidence standard."),
    ("handoff", "Next batch may continue from 13,397 if this closes; do not infer tree food, use, material-source, habitat, place/story/country, ownership, target morphology, or support-inflection grammar from Rule 224.", "Rule 224: next cadence."),
]

LEXEMES = [
    ("jundul", "noun", None, "NA", "jundul tree", "batch-266: jundul-tree reference only; poison/leaching prose closed."),
    ("kabariji", "noun", None, "NA", "cherry tree", "batch-266: cherry-tree reference only; fruit/food prose closed."),
    ("kawunjil", "noun", None, "NA", "black cherry tree", "batch-266: black-cherry-tree reference only; fruit/sweetness/season prose closed."),
    ("kayjurr", "noun", None, "NA", "white gum", "batch-266: white-gum reference only."),
    ("kingal", "noun", None, "NA", "river oak", "batch-266: river-oak reference only; beach/habitat prose closed."),
    ("kulbar", "noun", None, "NA", "white beech", "batch-266: white-beech reference only; timber/material prose closed."),
    ("kumin", "noun", None, "NA", "kumin fig tree", "batch-266: kumin-fig-tree reference only; edible-fruit/season prose closed."),
    ("marbaji", "noun", None, "NA", "stringybark tree", "batch-266: stringybark-tree reference only."),
    ("milbanku", "noun", None, "NA", "pencil cedar", "batch-266: pencil-cedar reference only; edible seed-skin prose closed."),
    ("mujarr", "noun", None, "NA", "mujarr fig tree", "batch-266: mujarr-fig-tree reference only; edible fruit/trunk/colour/season prose closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-266: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-266: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-266: 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-266-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 224 rows. Morphology checked bare named-tree nouns and uninflected yinya/yaluy/yinyay support. Lexicon checked selected tree-reference labels 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 earlier tree/flora target reopening, place-heavy candidate, exact-collision candidate, fruit/food/seed/poison/leaching row, medicine row, bark-use row, timber/material-source row, ecology/habitat row, place/story/country row, ownership row, target case, number morphology, derivation, productive compounding, productive reduplication, support inflection, or recent fauna-reference 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 224 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_266.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 224 targets and support heads.",
        artifact_path="batch_scripts/close_266.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 266: 50 accepted Rule 224 low-coverage named tree-reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_266.py",
        artifact_path="batch_scripts/close_266.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())
