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

NOTES = (
    "NATIVE MAMMAL REFERENCE LEXICAL EXPANSION AFTER RULE 176 (Rule 177). 50 rows. TARGETS: bimbarrbay scrub "
    "wallaby, durrkin white-tailed rat, jibul large bat, kirbaji dugong, jumar little wallaby, murrumu dingo, "
    "nyarrkali black kangaroo, wambiji platypus, waykal native cat, and yalmburrajaka whale. FRAMES: bare yaluy "
    "deictic identification, bare present perception with ngayu, yinyay-supported present perception with yundu, "
    "yinyay-supported past perception with jana, and yaluy-supported present perception with ngana. REVIEW: all "
    "targets stayed bare; no dog/pig/horse/cat-loan drift, introduced-animal row, place/story/cave sense, "
    "iron/clothing/source-material extension, food, hunting, catching, biting, killing, habitat/ecology, body-part, "
    "target case, target compound, possession, plural derivation, or event semantics."
)

LESSONS = [
    ("process", "A lexical pass after Rule 176 selected a bounded native mammal-reference field with exact dictionary readback.", "Rule 177: native mammal lexical cadence."),
    ("process", "Rule 177 preferred zero-hit or low-hit heads instead of recycling common older animal rows.", "Rule 177: additive target discipline."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 177: duplicate preflight."),
    ("process", "Dog, pig, horse, cat-loan, introduced-animal, and old mammal heads outside the selected set stayed closed.", "Rule 177: old mammal exclusion."),
    ("process", "`jibul` was admitted only as large bat; the cave/place/story-site prose remains closed.", "Rule 177: jibul sense discipline."),
    ("lexicon", "`bimbarrbay` is scrub wallaby only; no habitat, hunting, or event row.", "Rule 177: bimbarrbay."),
    ("lexicon", "`durrkin` is white-tailed rat only; no tail/body-part row.", "Rule 177: durrkin."),
    ("lexicon", "`jibul` is large bat only; no cave, place-name, Kangkaji/Kaway/Kurrbi, or story-site row.", "Rule 177: jibul."),
    ("lexicon", "`kirbaji` is dugong only; no sea, water, hunting, food, iron, or event row.", "Rule 177: kirbaji."),
    ("lexicon", "`jumar` is little wallaby only; no size predicate, hunting, food, or event row.", "Rule 177: jumar."),
    ("lexicon", "`murrumu` is dingo only; no dog/loan drift, attack, biting, or event row.", "Rule 177: murrumu."),
    ("lexicon", "`nyarrkali` is black kangaroo only; no colour-predicate, hunting, food, or event row.", "Rule 177: nyarrkali."),
    ("lexicon", "`wambiji` is platypus only; no river, water, habitat, or event row.", "Rule 177: wambiji."),
    ("lexicon", "`waykal` is native cat only; no cat-loan, introduced-cat, hunting, or event row.", "Rule 177: waykal."),
    ("lexicon", "`yalmburrajaka` is whale only; no sea, ocean, food, hunting, or event row.", "Rule 177: yalmburrajaka."),
    ("morphology", "All target heads stayed bare; no target LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, reduplicated, or compound morphology was produced.", "Rule 177: target case restraint."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 177: perception tense forms."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 177: pronoun A marking."),
    ("morphology", "`yaluy` and `yinyay` stayed uninflected local demonstratives, not target case morphology.", "Rule 177: local demonstrative restraint."),
    ("syntax", "Rows 1-10 used one mammal target plus `yaluy` with no predicator.", "Rule 177: yaluy deictic syntax."),
    ("syntax", "Rows 11-20 used bare 1sg A plus one bare mammal object and `nyajil`.", "Rule 177: bare present perception."),
    ("syntax", "Rows 21-30 used bare 2sg A, one bare mammal object, `yinyay`, and `nyajil`.", "Rule 177: yundu yinyay perception."),
    ("syntax", "Rows 31-40 used bare 3pl A, one bare mammal object, `yinyay`, and past `nyajin`.", "Rule 177: jana yinyay past perception."),
    ("syntax", "Rows 41-50 used inclusive `ngana`, one bare mammal object, `yaluy`, and `nyajil`.", "Rule 177: ngana yaluy perception."),
    ("handoff", "Next cadence can consolidate the Rule 177 mammal set, but dog/loan, place/story, habitat, food, hunting, body-part, target-case, and event semantics remain closed unless deliberately sourced.", "Rule 177: next cadence."),
]

LEXEMES = [
    ("bimbarrbay", "noun", None, "NA", "scrub wallaby", "batch-219: selected scrub wallaby only; no habitat, hunting, food, or event row."),
    ("durrkin", "noun", None, "NA", "white-tailed rat", "batch-219: selected white-tailed rat only; no tail/body-part row."),
    ("jibul", "noun", None, "NA", "large bat", "batch-219: selected large bat only; cave/place/story-site prose remains closed."),
    ("kirbaji", "noun", None, "NA", "dugong", "batch-219: selected dugong only; no sea, water, hunting, food, iron, or event row."),
    ("jumar", "noun", None, "NA", "little wallaby", "batch-219: selected little wallaby only; no size predicate, hunting, food, or event row."),
    ("murrumu", "noun", None, "NA", "dingo", "batch-219: selected dingo only; no dog/loan drift, attack, biting, or event row."),
    ("nyarrkali", "noun", None, "NA", "black kangaroo", "batch-219: selected black kangaroo only; no colour predicate, hunting, food, or event row."),
    ("wambiji", "noun", None, "NA", "platypus", "batch-219: selected platypus only; no river, water, habitat, or event row."),
    ("waykal", "noun", None, "NA", "native cat", "batch-219: selected native cat only; no cat-loan, introduced-cat, hunting, or event row."),
    ("yalmburrajaka", "noun", None, "NA", "whale", "batch-219: selected whale only; no sea, ocean, food, hunting, or event row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-219: retained local demonstrative in deictic and supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-219: retained local demonstrative in supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-219: retained past and nonpast perception rows with native mammal objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-219: bare pronoun A in present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-219: bare pronoun A in yinyay-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-219: bare pronoun A in yinyay-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-219: bare pronoun A in yaluy-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-219-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 177 rows. Morphology checked bare mammal targets, no target case/compound/possessive/instrument/comitative/plural/reduplicated forms, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected mammal senses and kept dog/pig/horse/cat-loan, old mammal heads, place/story/cave, iron/clothing/source-material, food, hunting, catching, biting, killing, habitat/ecology, body-part, and target-case traps closed. Syntax checked bare yaluy deictic identification, bare present perception, yinyay-supported present and past perception, and yaluy-supported present perception. Fidelity checked no source-prose use import. Register stayed ordinary reference/perception.",
                 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/reduplicated/compound form, no dog/pig/horse/cat-loan drift, no place/story/cave extension, no habitat/food/hunting/body-part/source-material/event claim, and no nonselected mammal target.",
                 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 177 lessons covering source checks, old-head exclusion, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_219.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 177 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_219.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 219: 50 accepted Rule 177 native mammal reference lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_219.py", artifact_path="batch_scripts/close_219.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-219:%'").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())
