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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 153 (Rule 154). 50 rows. RETAINED TARGETS: kaba rain, muyar wind, "
    "ngurrban cloud, wungar sun, kija moon, yiril rainbow, jarramali thunderstorm, jabulbina thunder, "
    "kurrubijal morning star, wurunurru whirlwind. FRAMES: bare deictic identification with yinyay/yaluy; present "
    "and past yaluy-supported perception with ngayu, yundu, jana, and ngamu-ngku. REVIEW: no new target heads, all "
    "targets bare, no weather-event predicates, no target case/compound forms, no season/time expressions, no "
    "place-name drift, no kija month/place drift, no jarramali animal/temper senses, and no carry-forward "
    "geography/implement inference."
)

LESSONS = [
    ("process", "A construction consolidation pass after a lexical weather/sky batch should reuse target heads without opening new event semantics.", "Rule 154: construction after lexical pass."),
    ("process", "Rule 154 admitted no new target heads and used only yinyay/yaluy deictic support plus nyaji-l perception.", "Rule 154: no-new-target discipline."),
    ("process", "Exact duplicate preflight caught old `Yiril yinyay.` and the row was revised to `Yiril yaluy.` before banking.", "Rule 154: duplicate preflight changed content."),
    ("lexicon", "`kaba` stayed rain noun only; no rain-fall, rain-coming, rainbird, rainforest, or place-name row.", "Rule 154: kaba retained scope."),
    ("lexicon", "`muyar` stayed wind noun only; no wind-coming, blowing, or potent weather-agent row.", "Rule 154: muyar retained scope."),
    ("lexicon", "`ngurrban` stayed cloud noun only; no fog, cloud-cover, or prediction inference.", "Rule 154: ngurrban retained scope."),
    ("lexicon", "`wungar` stayed sun noun only; no hot-season, day/time, sunrise, sunset, or heat predicate.", "Rule 154: wungar retained scope."),
    ("lexicon", "`kija` stayed moon noun only; month, cold, Roaring Meg, and place-name senses stayed closed.", "Rule 154: kija moon-only."),
    ("lexicon", "`yiril` stayed rainbow noun only; no story, omen, or rainbow-serpent inference.", "Rule 154: yiril retained scope."),
    ("lexicon", "`jarramali` stayed thunderstorm weather sense only; animal and temper senses stayed closed.", "Rule 154: jarramali retained scope."),
    ("lexicon", "`jabulbina` stayed thunder only, not a generic storm or omen field.", "Rule 154: jabulbina retained scope."),
    ("lexicon", "`kurrubijal` stayed morning star only; no time-of-day or travel-by-star claim.", "Rule 154: kurrubijal retained scope."),
    ("lexicon", "`wurunurru` stayed whirlwind only; no movement-event or danger row.", "Rule 154: wurunurru retained 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 154: target case restraint."),
    ("morphology", "`yaluy` and `yinyay` were support deictics only and were not attached to target heads.", "Rule 154: deictic support restraint."),
    ("morphology", "Common-noun A `ngamu-ngku` was ERG-marked; pronoun A `ngayu`, `yundu`, and `jana` stayed bare.", "Rule 154: A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast, glossed as seeing/hearing according to the target.", "Rule 154: perception tense forms."),
    ("syntax", "Bare deictic-identification rows used one weather/sky target plus `yinyay` or `yaluy` and no predicator.", "Rule 154: deictic identification syntax."),
    ("syntax", "Present perception rows used one bare weather/sky object plus `yaluy` and `nyajil`.", "Rule 154: present perception syntax."),
    ("syntax", "Past perception rows used one bare weather/sky object plus `yaluy` and `nyajin`.", "Rule 154: past perception syntax."),
    ("syntax", "Second-person `yundu` was used as a bare pronoun A in the established nyaji-l perception frame.", "Rule 154: yundu perception 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 154: 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 154: no source-event import."),
    ("register", "Rows remained ordinary deictic/perception clauses, not ceremonial, etiological, or encyclopedic claims.", "Rule 154: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but keep Rule 153-154 weather-event and polysemy traps closed unless deliberately sourced.", "Rule 154: next cadence."),
]

LEXEMES = [
    ("kaba", "noun", None, "NA", "rain", "batch-196: retained rain noun only in deictic/perception rows; no event/place-name row."),
    ("muyar", "noun", None, "NA", "wind", "batch-196: retained wind noun only; no wind-coming/blowing row."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-196: retained cloud noun only; no fog/prediction inference."),
    ("wungar", "noun", None, "NA", "sun", "batch-196: retained sun noun only; no hot-season/day/time row."),
    ("kija", "noun", None, "NA", "moon", "batch-196: retained moon noun only; month/cold/place-name senses closed."),
    ("yiril", "noun", None, "NA", "rainbow", "batch-196: retained rainbow noun only; old Yiril yinyay duplicate avoided."),
    ("jarramali", "noun", None, "NA", "thunderstorm", "batch-196: retained thunderstorm weather sense only; animal/temper senses closed."),
    ("jabulbina", "noun", None, "NA", "thunder", "batch-196: retained thunder noun only; no generic storm/omen field."),
    ("kurrubijal", "noun", None, "NA", "morning star", "batch-196: retained morning-star noun only; no time/travel inference."),
    ("wurunurru", "noun", None, "NA", "whirlwind", "batch-196: retained whirlwind noun only; no motion-event/danger row."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-196: retained local demonstrative in deictic identification rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-196: retained local demonstrative in deictic and perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-196: retained past and nonpast perception rows with yaluy support."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-196: bare pronoun A in perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-196: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-196: bare pronoun A in past perception rows."),
    ("ngamu", "noun", None, "NA", "mother", "batch-196: common-noun A in perception rows, ERG-marked."),
]


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-196-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 154 rows. Morphology checked bare weather/sky targets, no target case/compound forms, yinyay/yaluy support only, 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 deictic identification, present perception, past perception, second-person perception, and ngamu-ngku 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 new target head, 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 154 lessons covering process, retained lexical senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_196.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 154 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_196.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 196: 50 accepted Rule 154 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_196.py", artifact_path="batch_scripts/close_196.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-196:%'").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())
