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

NOTES = (
    "WEATHER/SKY LEXICAL EXPANSION AFTER RULE 152 (Rule 153). 50 rows. TARGETS: kaba rain, muyar wind, "
    "ngurrban cloud, wungar sun, kija moon, yiril rainbow, jarramali thunderstorm, jabulbina thunder, "
    "kurrubijal morning star, wurunurru whirlwind. FRAMES: present perception, bare past perception, and "
    "present/past perception with yinyay support. REVIEW: all targets stayed bare; no target case forms, compounds, "
    "rain-fall/wind-coming/weather-event predicates, season expressions, place-name drift, kija month/place drift, "
    "jarramali animal/temper senses, or carry-forward geography/implement inference."
)

LESSONS = [
    ("process", "A weather/sky lexical pass should use perception frames before opening event predicates like rain falling or wind coming.", "Rule 153: lexical before weather events."),
    ("process", "Rule 153 admitted ten weather/sky targets and kept all target heads bare.", "Rule 153: target inventory."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 153: duplicate preflight."),
    ("lexicon", "`kaba` was admitted as rain noun only; no rain-fall, rainbird, rain forest, or place-name row.", "Rule 153: kaba lexical scope."),
    ("lexicon", "`muyar` was admitted as wind noun only; no wind-coming, blowing, or potent weather-agent row.", "Rule 153: muyar lexical scope."),
    ("lexicon", "`ngurrban` was admitted as cloud noun only; no fog or cloud-cover inference.", "Rule 153: ngurrban lexical scope."),
    ("lexicon", "`wungar` was admitted as sun noun only; no hot-season, day/time, sunrise, or sunset row.", "Rule 153: wungar lexical scope."),
    ("lexicon", "`kija` was admitted as moon noun only; month, cold relapse, and Roaring Meg/place-name senses stayed closed.", "Rule 153: kija moon-only."),
    ("lexicon", "`yiril` was admitted as rainbow noun only; no rainbow-serpent or story inference.", "Rule 153: yiril lexical scope."),
    ("lexicon", "`jarramali` was admitted as thunderstorm weather sense only; praying mantis, stingray, angry-person, and hot-head senses stayed closed.", "Rule 153: jarramali weather sense."),
    ("lexicon", "`jabulbina` was admitted as thunder only, not as a generic storm or omen field.", "Rule 153: jabulbina lexical scope."),
    ("lexicon", "`kurrubijal` was admitted as morning star only; no time-of-day or travel-by-star row.", "Rule 153: kurrubijal lexical scope."),
    ("lexicon", "`wurunurru` was admitted as whirlwind only; no motion-event or danger row.", "Rule 153: wurunurru lexical scope."),
    ("morphology", "All weather/sky target heads stayed bare; no target LOC, DAT, ABL, PERL, INST, COMIT, POSS, season compound, or other target compound morphology appeared.", "Rule 153: target case restraint."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 153: A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast, glossed as seeing/hearing according to the target.", "Rule 153: perception tense forms."),
    ("syntax", "Present perception rows used one bare weather/sky object plus `nyajil`.", "Rule 153: present perception syntax."),
    ("syntax", "Bare past perception rows used one bare weather/sky object plus `nyajin`.", "Rule 153: past perception syntax."),
    ("syntax", "Perception rows with `yinyay` added deictic support without target case morphology.", "Rule 153: deictic perception syntax."),
    ("syntax", "No row used weather-event predication, target locative, target perlative, target dative goal, or route construction.", "Rule 153: no event syntax."),
    ("fidelity", "English labels selected only source-attested weather/sky senses and did not add motion, causation, omen, story-site, season, or animal inference.", "Rule 153: selected-sense fidelity."),
    ("fidelity", "No rain falling, wind blowing/coming, thunderstorm coming, sunrise, sunset, season, month, or place-name frame was imported from source examples.", "Rule 153: no source-event import."),
    ("register", "Rows remained ordinary weather/sky perception statements.", "Rule 153: register scope."),
    ("handoff", "Next cadence should consolidate these weather/sky heads before opening weather-event predicates.", "Rule 153: next cadence."),
    ("handoff", "Carry forward the traps: keep `kija` moon-only, `jarramali` weather-only, `wungar` sun-only, and avoid `kaba-kada` place-name drift.", "Rule 153: carry-forward traps."),
]

LEXEMES = [
    ("kaba", "noun", None, "NA", "rain", "batch-195: rain noun only; no fall/come/rainbird/rain-forest/place-name row."),
    ("muyar", "noun", None, "NA", "wind", "batch-195: wind noun only; no wind-coming/blowing/potent-agent row."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-195: cloud noun only; no fog or cloud-cover inference."),
    ("wungar", "noun", None, "NA", "sun", "batch-195: sun noun only; no hot-season/day/time/sunrise/sunset row."),
    ("kija", "noun", None, "NA", "moon", "batch-195: moon noun only; month/cold/place-name senses closed."),
    ("yiril", "noun", None, "NA", "rainbow", "batch-195: rainbow noun only; no rainbow-serpent/story inference."),
    ("jarramali", "noun", None, "NA", "thunderstorm", "batch-195: thunderstorm weather sense only; animal/temper senses closed."),
    ("jabulbina", "noun", None, "NA", "thunder", "batch-195: thunder noun only; not generic storm/omen field."),
    ("kurrubijal", "noun", None, "NA", "morning star", "batch-195: morning-star noun only; no time/travel inference."),
    ("wurunurru", "noun", None, "NA", "whirlwind", "batch-195: whirlwind noun only; no motion-event/danger row."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-195: retained local demonstrative support in perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-195: retained past and nonpast perception rows with weather/sky objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-195: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-195: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-195: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-195: bare pronoun A in perception rows."),
]


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-195-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 153 rows. Morphology checked bare weather/sky targets, no target case/compound forms, common-noun A ERG, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected weather/sky senses and closed polysemy traps. Syntax checked present, past, and yinyay-supported perception. Fidelity checked no weather-event/place-name/season import. Register stayed ordinary.",
                 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 locative/dative/ablative/perlative/instrument/comitative/possessive/compound form, no rain-fall/wind-coming/thunderstorm-coming/sunrise/sunset/season/month/place-name row, no jarramali animal/temper row, and no carry-forward geography/implement semantics.",
                 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 153 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_195.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 153 targets, support forms, participants, and pronouns.",
                 artifact_path="batch_scripts/close_195.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 195: 50 accepted Rule 153 weather/sky lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_195.py", artifact_path="batch_scripts/close_195.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 = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    under_review_remaining = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    lesson_count = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (batch_id,)).fetchone()[0]
    lexeme_logs = db.execute("SELECT COUNT(*) FROM lexeme_log WHERE detail LIKE '%batch-195:%'").fetchone()[0]
    process_events = db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (LABEL,)).fetchone()[0]
    print(f"closed {LABEL}: 50 accepted rows, {reviews} review passes, {lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, {process_events} process events, under_review={under_review_remaining}, verified corpus={verified}")
    return 0


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