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

NOTES = (
    "DEICTIC SOUND-REFERENCE CONSTRUCTION CONSOLIDATION AFTER RULE 201 (Rule 202). 50 rows. TARGETS retained from "
    "Rule 201: kawal cooee, ngawungkal halloo, ngulnkul hum, nyinja grunt, wungka wail, kandarr belch, ngangkun "
    "hiccups, wankun hiccoughs, warimaji yawn, and kunji sneeze. FRAMES: TARGET yaluy, TARGET yinyay, Yinya TARGET "
    "yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. REVIEW: all targets stayed bare sound nouns; yinya/yaluy/"
    "yinyay stayed demonstrative/local support only; no nyaji-l/hearing/perception row was opened. No previous "
    "sound-batch heads, sound-making verbs, source persons/animals, dog/pig/motor/food sources, chewing/noisy-eating "
    "row, woman-in-distress narrative, mourning/death story, sickness/illness diagnosis, body-part possession, "
    "proximal yala/yanyu decision, target-case, compound, plural, derivation, productive reduplication, tree-reference, "
    "or demonstrative-inflection row was opened."
)

LESSONS = [
    ("process", "Rule 202 consolidated the Rule 201 sound nouns rather than adding new lexemes.", "Rule 202: consolidation after lexical expansion."),
    ("process", "The construction target was deictic/presentational reference, not hearing/perception.", "Rule 202: construction scope."),
    ("process", "Exact duplicate preflight over all 50 planned deictic sound-reference surfaces returned no cross-corpus accepted/revised/under_review collisions.", "Rule 202: duplicate preflight."),
    ("source", "Patz 3.7 supports Yalanji yinya as 'that/those'.", "Rule 202: yinya source."),
    ("source", "Patz 3.7 supports Yalanji yaluy as 'here' and yinyay as 'there'.", "Rule 202: local demonstrative source."),
    ("source", "Patz 3.7 states demonstrative pronouns imply singular or plural according to context and may refer to animate or inanimate beings.", "Rule 202: yinya number/animacy."),
    ("source", "Patz 4.1 supports yinya before or after a single noun, e.g. yinya karrkay/karrkay yinya.", "Rule 202: demonstrative order source."),
    ("source", "Rule 200 supplied corpus precedent for Yinya TARGET yinyay and TARGET yinya yinyay as safe distal-demonstrative presentation frames.", "Rule 202: local corpus precedent."),
    ("lexicon", "Kawal remained cooee only, not shouting, calling, or a source-person event.", "Rule 202: kawal cooee only."),
    ("lexicon", "Ngawungkal remained halloo only, not a far-away caller event.", "Rule 202: ngawungkal halloo only."),
    ("lexicon", "Ngulnkul remained hum only, not humming, tune-making, or voice-event narration.", "Rule 202: ngulnkul hum only."),
    ("lexicon", "Nyinja remained grunt only, not a pig/animal-source event.", "Rule 202: nyinja grunt only."),
    ("lexicon", "Wungka remained wail only, not woman-in-distress, screaming, swearing, mourning, or narrative content.", "Rule 202: wungka wail only."),
    ("lexicon", "Kandarr remained belch/burp only, not a body-state or source-person event.", "Rule 202: kandarr belch only."),
    ("lexicon", "Ngangkun remained hiccups/hiccoughs only, not illness or diagnosis.", "Rule 202: ngangkun hiccups only."),
    ("lexicon", "Wankun remained hiccoughs only, not illness or diagnosis.", "Rule 202: wankun hiccoughs only."),
    ("lexicon", "Warimaji remained yawn only, not sleep state or source-person event.", "Rule 202: warimaji yawn only."),
    ("lexicon", "Kunji remained sneeze only, not sickness or fire homograph drift.", "Rule 202: kunji sneeze only."),
    ("lexicon", "Previous sound heads jangkuy, kankar, nginja, numburr, yanja, kadil, kuwimbur, ngangkurr, and ngingkirr stayed closed.", "Rule 202: previous sound-batch heads closed."),
    ("lexicon", "Proximal demonstratives yala and yanyu stayed closed; this batch used only distal yinya plus yaluy/yinyay.", "Rule 202: proximal demonstratives closed."),
    ("morphology", "All sound targets stayed bare: no target locative, dative, ablative, perlative, ergative, instrumental, comitative, possessive, privative, degree, plural, compound, derivation, or productive reduplication.", "Rule 202: bare target morphology."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads; no demonstrative case table was expanded.", "Rule 202: support morphology restraint."),
    ("morphology", "No nyaji-l, nyajil, or nyajin appeared in Rule 202 rows.", "Rule 202: no hearing morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 202: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 202: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 202: initial demonstrative there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 202: postposed demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 202: initial demonstrative here frame."),
    ("fidelity", "English stayed literal and reference-only: the/that/those sound noun plus here/there.", "Rule 202: literal English."),
    ("fidelity", "Plural English was used only where the selected English sense is conventionally plural: hiccups and hiccoughs.", "Rule 202: English number discipline."),
    ("fidelity", "No English source person/animal, dog, pig, motor, food, chewing, shouting event, singing event, hearing, illness, distress, mourning, death, body-part, place, country, tree, material, or making wording was imported.", "Rule 202: denied English fields."),
    ("register", "Rows remained plain deictic references to sound nouns, not event reports, social narratives, illness narratives, bodily-source descriptions, animal-source descriptions, or food/eating scenes.", "Rule 202: reference register."),
    ("handoff", "Next batch should either open a fresh bounded lexical field or consolidate this sound set in another already sourced construction; source/event/illness/body-state traps remain closed.", "Rule 202: next cadence."),
]

LEXEMES = [
    ("kawal", "noun", None, "NA", "cooee; shout", "batch-244: deictic sound-reference target only; no shouting event or source person."),
    ("ngawungkal", "noun", None, "NA", "halloo; shout from far away", "batch-244: deictic sound-reference target only; no source-person event."),
    ("ngulnkul", "noun", None, "NA", "hum; voice without words", "batch-244: deictic sound-reference target only; no humming/tune-making event."),
    ("nyinja", "noun", None, "NA", "grunt", "batch-244: deictic sound-reference target only; no animal/source event."),
    ("wungka", "noun", None, "NA", "wail; scream", "batch-244: wail target only; no distress narrative or source person."),
    ("kandarr", "noun", None, "NA", "belch; burp", "batch-244: body-sound target only; no body-state source event."),
    ("ngangkun", "noun", None, "NA", "hiccups; hiccoughs", "batch-244: body-sound target only; no illness/diagnosis."),
    ("wankun", "noun", None, "NA", "hiccoughs", "batch-244: body-sound target only; no illness/diagnosis."),
    ("warimaji", "noun", None, "NA", "yawn", "batch-244: body-sound target only; no source-person event."),
    ("kunji", "noun", None, "NA", "sneeze", "batch-244: body-sound target only; no sickness/diagnosis."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-244: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-244: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those; there", "batch-244: distal demonstrative support only; no new 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-244-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 202 rows. Morphology checked target heads bare, yinya/yaluy/yinyay uninflected, and no nyaji-l forms. Lexicon checked ten retained sound/body-sound senses and kept previous sound heads, source persons/animals, food/eating, illness, distress, mourning, body-part, tree, and event semantics closed. Syntax checked five deictic/presentational frames. Fidelity checked literal here/there/that/those English. Register stayed plain sound-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 nyaji-l, hearing/listening/perception rows, previous sound-batch heads, sound-making verbs, source-person/animal rows, dog/pig/motor/food source, chewing/noisy-eating row, woman-in-distress narrative, mourning/death story, sickness/illness diagnosis, body-part possession, proximal yala/yanyu decision, target case, compound, plural, derivation, productive reduplication, tree-reference, or demonstrative-inflection row.",
        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 202 lessons covering source checks, target senses, prior-head closures, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_244.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 202 sound targets and demonstrative support heads.",
        artifact_path="batch_scripts/close_244.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 244: 50 accepted Rule 202 deictic sound-reference construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_244.py",
        artifact_path="batch_scripts/close_244.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-244%'").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, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_review_remaining}, verified corpus={verified}"
    )
    return 0


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