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

NOTES = (
    "PERCEPTION-REFERENCE CONSTRUCTION CONSOLIDATION AFTER RULE 191 (Rule 192). 50 rows. RETAINED TARGETS: "
    "jangkuy chewing sound, ngurma-mulkaynji image, kankar clap sound, nginja grunt sound, numburr rattling sound, "
    "yanja rustling noise, kadil sharp sound, kuwimbur whistle sound, ngangkurr barking sound, and ngurma reflection. "
    "FRAMES: bare yinyay deictic identification, yaluy-supported present perception with ngayu, yaluy-supported "
    "present perception with yundu, yaluy-supported past perception with jana, and yinyay-supported present perception "
    "with ngana. REVIEW: all targets stayed bare; no new target heads, sound-making events, smell/taste verbs, source "
    "events, rejected candidates, perception compounds, target case, target compounds, plural derivation, productive "
    "reduplication, or post-contact object drift."
)

LESSONS = [
    ("process", "Rule 192 deliberately consolidated the bounded Rule 191 perception-reference field rather than adding targets.", "Rule 192: construction cadence after Rule 191."),
    ("process", "The source pass retained exactly ten Rule 191 heads and reopened no rejected near candidate.", "Rule 192: retained target inventory."),
    ("process", "`jadal-jadal` stayed closed because it is adjectival and imports missed-hearing/weakness semantics.", "Rule 192: jadal-jadal rejection retained."),
    ("process", "`jila-burra` stayed closed because bad smell needs an olfactory frame, not `nyaji-l` perception-reference consolidation.", "Rule 192: jila-burra rejection retained."),
    ("process", "`kubarru`, `ngingkirr`, and `ngaru` stayed closed because they import whip/event, example-sentence/pig-event, and adjectival voice-quality traps.", "Rule 192: other rejections retained."),
    ("lexicon", "`jangkuy` was retained as chewing sound only; eating, food, mouth, and chewing-event rows stayed closed.", "Rule 192: jangkuy retained."),
    ("lexicon", "`ngurma-mulkaynji` was retained as image only; picture/statue/movie/cards, mirror, water, shadow-spirit, and post-contact object rows stayed closed.", "Rule 192: ngurma-mulkaynji retained."),
    ("lexicon", "`kankar` was retained as clap sound only; clapping action and hand/body-part rows stayed closed.", "Rule 192: kankar retained."),
    ("lexicon", "`nginja` was retained as grunt sound only; pig, dog, roaring, growling, and grunting-event rows stayed closed.", "Rule 192: nginja retained."),
    ("lexicon", "`numburr` was retained as rattling sound only; motor, machine, and vehicle rows stayed closed.", "Rule 192: numburr retained."),
    ("lexicon", "`yanja` was retained as rustling noise only; wind, tree, grass, motion, and warning rows stayed closed.", "Rule 192: yanja retained."),
    ("lexicon", "`kadil` was retained as sharp sound only; axe, cutting, wood, tree-fall, danger, and event rows stayed closed.", "Rule 192: kadil retained."),
    ("lexicon", "`kuwimbur` was retained as whistle sound only; whistling action, song, bird-bone, making, and instrument rows stayed closed.", "Rule 192: kuwimbur retained."),
    ("lexicon", "`ngangkurr` was retained as barking sound only; dog, barking event, source, and movement rows stayed closed.", "Rule 192: ngangkurr retained."),
    ("lexicon", "`ngurma` was retained as reflection only; picture/statue/movie/cards, mirror, water, shadow-spirit, and post-contact object rows stayed closed.", "Rule 192: ngurma retained."),
    ("morphology", "All Rule 192 target heads stayed bare with zero absolutive object marking.", "Rule 192: bare target morphology."),
    ("morphology", "No target locative, dative, ablative, perlative, ergative, instrumental, comitative, possessive, privative, excess, plural, compound, or productive-reduplicated form was admitted.", "Rule 192: target case restraint."),
    ("morphology", "`ngurma-mulkaynji` stayed a dictionary compound head; no target-compound productivity was inferred.", "Rule 192: lexical compound distinction."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast, glossed as perceive because the object field is auditory and visual.", "Rule 192: perception tense forms."),
    ("syntax", "Rows 1-10 used one retained target noun plus `yinyay` with no predicator.", "Rule 192: yinyay deictic syntax."),
    ("syntax", "Rows 11-20 used bare `ngayu`, one bare target, `yaluy`, and present `nyajil`.", "Rule 192: ngayu yaluy perception."),
    ("syntax", "Rows 21-30 used bare `yundu`, one bare target, `yaluy`, and present `nyajil`.", "Rule 192: yundu yaluy perception."),
    ("syntax", "Rows 31-40 used bare `jana`, one bare target, `yaluy`, and past `nyajin`.", "Rule 192: jana yaluy past perception."),
    ("syntax", "Rows 41-50 used inclusive `ngana`, one bare target, `yinyay`, and present `nyajil`.", "Rule 192: ngana yinyay perception."),
    ("handoff", "Next cadence may return to lexical expansion, but only after a fresh source pass and with Rule 191-192 traps carried forward.", "Rule 192: next cadence."),
]

LEXEMES = [
    ("jangkuy", "noun", None, "NA", "chewing sound", "batch-234: retained as sound of chewing only in construction consolidation; no eating, food, mouth, or chewing-event row."),
    ("ngurma-mulkaynji", "noun", None, "NA", "image", "batch-234: retained as image only in construction consolidation; no picture/statue/movie/cards, mirror, water, or shadow-spirit row."),
    ("kankar", "noun", None, "NA", "clap sound", "batch-234: retained as sound of a clap only in construction consolidation; no clapping action or hand/body-part row."),
    ("nginja", "noun", None, "NA", "grunt sound", "batch-234: retained as grunt sound only in construction consolidation; no pig, dog, roar, growl, or grunt-event row."),
    ("numburr", "noun", None, "NA", "rattling sound", "batch-234: retained as rattling sound only in construction consolidation; no motor, machine, or vehicle row."),
    ("yanja", "noun", None, "NA", "rustling noise", "batch-234: retained as rustling noise only in construction consolidation; no wind, tree, grass, motion, or warning row."),
    ("kadil", "noun", None, "NA", "sharp sound", "batch-234: retained as sharp/crashing sound only in construction consolidation; no axe, cutting, wood, tree-fall, danger, or event row."),
    ("kuwimbur", "noun", None, "NA", "whistle sound", "batch-234: retained as whistle sound only in construction consolidation; no whistling action, song, bird-bone, making, or instrument row."),
    ("ngangkurr", "noun", None, "NA", "barking sound", "batch-234: retained as barking sound only in construction consolidation; no dog, barking event, source, or movement row."),
    ("ngurma", "noun", None, "NA", "reflection", "batch-234: retained as reflection only in construction consolidation; no picture/statue/movie/cards, mirror, water, or shadow-spirit row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-234: retained local demonstrative in supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-234: retained distal demonstrative in deictic and supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-234: retained past and nonpast perception rows with perception-reference nouns."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-234: bare pronoun A in yaluy-supported present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-234: bare pronoun A in yaluy-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-234: bare pronoun A in yaluy-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-234: bare pronoun A in yinyay-supported present 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-234-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 192 rows. Morphology checked bare retained targets, no target case/compound/possessive/instrument/comitative/plural/productive-reduplication forms, ngurma-mulkaynji as dictionary compound only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected dictionary senses and kept rejected candidates, sound-making events, source-prose events, animal/motor/wind/tree/grass/axe/whip/song/mirror/water/post-contact-object drift, and perception compounds closed. Syntax checked yinyay bare deictic identification, yaluy-supported present perception with ngayu and yundu, yaluy-supported past perception with jana, and yinyay-supported present perception with ngana. Fidelity checked no source-event import. Register stayed ordinary perception/reference.",
                 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/ergative/instrument/comitative/possessive/privative/excess/plural/productive-reduplication/compound form, no loan token, no rejected target, no sound-making event, no source-event drift, and no new perception compound.",
                 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 192 lessons covering source checks, construction scope, rejected candidates, retained target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_234.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 192 retained targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_234.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 234: 50 accepted Rule 192 perception-reference construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_234.py", artifact_path="batch_scripts/close_234.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 action LIKE 'batch-234%'").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())
