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

NOTES = (
    "LOW-COVERAGE WEATHER-CONDITION REFERENCE LEXICAL EXPANSION AFTER RULE 226 (Rule 227). 50 rows. TARGETS: "
    "balbay lightning, jiri bajaku cloudless sky/fine day, jirimali fine day/cloudless sky, jukar-warra whirlwind, "
    "kumbamu trade wind, kurrinkurrin mackerel sky, nganyil haze, ngurrbal fog, wadjal cyclone, and wurrbal river mist. "
    "SUPPORT: yaluy/yinyay, nyaji-l perception with nyajil/nyajin, and bare pronoun A ngayu/ngana/yundu/jana. "
    "FRAMES: TARGET yaluy, Ngayu TARGET yinyay nyajil, Ngana TARGET yinyay nyajil, Yundu TARGET yaluy nyajil, "
    "and Jana TARGET yaluy nyajin. REVIEW: all target nouns stayed bare weather-condition reference labels. No Rule 153 "
    "exact-target repeat, weather-event predicate, prediction, omen/story/death/spirit row, season expression, target case, "
    "productive compound, productive reduplication, support inflection, or source-prose drift was opened."
)

LESSONS = [
    ("process", "Rule 227 selected low-coverage weather-condition references only after checking prior Rules 153-154, dictionary entries, exact surfaces, and lint behavior.", "Rule 227: weather-condition cadence."),
    ("source", "Rules 153-154 already source weather/sky heads in nyaji-l perception and bare deictic support frames; Rule 227 reuses those frames for new low-coverage heads.", "Rule 227: construction source."),
    ("source", "Patz section 3.7 and the existing corpus law support yaluy and yinyay as uninflected local demonstrative support.", "Rule 227: local support."),
    ("source", "Nyaji-l remains a broad see/hear/perceive predicate; English chooses see for visible weather and hear for trade wind.", "Rule 227: perception source."),
    ("process", "Rejected or deferred candidates included Rule 153 exact targets, death/spirit/omen entries, moon/place/story entries, fire/pus/urine entries, flood/tide/season/cold/darkness entries, and wurunurru collision rows.", "Rule 227: rejected weather fields."),
    ("lexicon", "Balbay stayed lightning reference only; blocked balbay-nja/balbaynja strike forms stayed closed.", "Rule 227: balbay."),
    ("lexicon", "Jiri bajaku stayed cloudless-sky/fine-day reference only; no generic sky grammar or weather prediction was opened.", "Rule 227: jiri bajaku."),
    ("lexicon", "Jirimali stayed fine-day reference only; no time, season, or forecast row was opened.", "Rule 227: jirimali."),
    ("lexicon", "Jukar-warra stayed whirlwind reference only; the sand component stayed lexicalized and no sand/ground/source row was opened.", "Rule 227: jukar-warra."),
    ("lexicon", "Kumbamu stayed trade-wind reference only; no wind-coming, blowing, travel, or sailing row was opened.", "Rule 227: kumbamu."),
    ("lexicon", "Kurrinkurrin stayed mackerel-sky reference only; its solid reduplication is lexicalized and does not license productive reduplication.", "Rule 227: kurrinkurrin."),
    ("lexicon", "Nganyil stayed haze reference only; it was not collapsed into fog/cloud or made into a weather adjective.", "Rule 227: nganyil."),
    ("lexicon", "Ngurrbal stayed fog reference only; no prediction, cloud-cover, river-mist, or motion row was opened.", "Rule 227: ngurrbal."),
    ("lexicon", "Wadjal stayed cyclone reference only; no warning, damage, danger, or storm-action row was opened.", "Rule 227: wadjal."),
    ("lexicon", "Wurrbal stayed river-mist reference only; the dictionary's rising-from-river prose did not become a motion/event frame.", "Rule 227: wurrbal."),
    ("morphology", "All target weather-condition nouns stayed bare: no target case, possession, comitative, instrumental, locative, number, derivation, suffixing, or productive compounding.", "Rule 227: bare targets."),
    ("morphology", "Kurrinkurrin was admitted only as a dictionary headword; the lint whitelist marks it lexicalized, not productive reduplication.", "Rule 227: lexicalized reduplication."),
    ("morphology", "Yaluy, yinyay, nyajil, and nyajin stayed uninflected support/predicate forms.", "Rule 227: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 227: deictic frame."),
    ("syntax", "Rows 11-20 used Ngayu TARGET yinyay nyajil.", "Rule 227: 1sg perception frame."),
    ("syntax", "Rows 21-30 used Ngana TARGET yinyay nyajil.", "Rule 227: 1pl perception frame."),
    ("syntax", "Rows 31-40 used Yundu TARGET yaluy nyajil.", "Rule 227: 2sg perception frame."),
    ("syntax", "Rows 41-50 used Jana TARGET yaluy nyajin.", "Rule 227: 3pl past perception frame."),
    ("fidelity", "English stayed literal reference/perception prose: target weather label plus here/there or see/hear.", "Rule 227: literal English."),
    ("fidelity", "The batch did not turn source definitions into weather events, warnings, predictions, story claims, death/spirit claims, season expressions, or storm-action reports.", "Rule 227: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference/perception statements, not forecasts, warnings, story-law, weather instruction, or event narrative.", "Rule 227: 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 227 as complete.", "Rule 227: evidence standard."),
    ("handoff", "Next batch may continue from 13,547 if this closes; do not infer weather-event, season, omen/story, death/spirit, target morphology, productive reduplication, or support-inflection grammar from Rule 227.", "Rule 227: next cadence."),
]

LEXEMES = [
    ("balbay", "noun", None, "NA", "lightning", "batch-269: lightning reference only; strike forms closed."),
    ("jiri bajaku", "noun", None, "NA", "cloudless sky; fine day", "batch-269: cloudless-sky/fine-day reference only."),
    ("jirimali", "noun", None, "NA", "fine day; cloudless sky", "batch-269: fine-day/cloudless-sky reference only."),
    ("jukar-warra", "noun", None, "NA", "whirlwind", "batch-269: whirlwind reference only; no sand/source row."),
    ("kumbamu", "noun", None, "NA", "trade wind", "batch-269: trade-wind reference only."),
    ("kurrinkurrin", "noun", None, "NA", "mackerel sky", "batch-269: lexicalized solid reduplicated weather headword only."),
    ("nganyil", "noun", None, "NA", "haze", "batch-269: haze reference only."),
    ("ngurrbal", "noun", None, "NA", "fog", "batch-269: fog reference only."),
    ("wadjal", "noun", None, "NA", "cyclone", "batch-269: cyclone reference only; no warning/damage row."),
    ("wurrbal", "noun", None, "NA", "river mist", "batch-269: river-mist reference only; no rising/event frame."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-269: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-269: local demonstrative support only."),
    ("nyajil", "verb-form", None, "NA", "see/hear/perceive nonpast", "batch-269: perception predicate support."),
    ("nyajin", "verb-form", None, "NA", "saw/heard/perceived", "batch-269: past perception predicate support."),
    ("ngayu", "pronoun", None, "NA", "I", "batch-269: bare pronoun A support."),
    ("ngana", "pronoun", None, "NA", "we", "batch-269: bare pronoun A support."),
    ("yundu", "pronoun", None, "NA", "you", "batch-269: bare pronoun A support."),
    ("jana", "pronoun", None, "NA", "they", "batch-269: bare pronoun A support."),
]


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-269-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 227 rows. Morphology checked bare weather-condition nouns and uninflected support. Lexicon checked selected weather-condition reference labels only. Syntax checked five deictic/perception frame bands. Fidelity checked literal reference/perception English. Register stayed plain reference/perception 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 Rule 153 exact-target repeat, weather-event predicate, prediction row, omen/story/death/spirit row, season expression, target case, target compound, productive reduplication, support inflection, fire/flood/tide/source drift, or recent body-part-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 227 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_269.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 227 targets and support heads.",
        artifact_path="batch_scripts/close_269.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 269: 50 accepted Rule 227 low-coverage weather-condition reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_269.py",
        artifact_path="batch_scripts/close_269.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())
