#!/usr/bin/env python3
"""Close batch-150 after main-loop five-lens review."""

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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-150"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "CONSTRUCTION: DEMONSTRATIVES, SPATIAL DEIXIS, AND PLACE-REFERENCE PARADIGMS (Rule 108). 50 rows. DESIGN: "
    "grammar-led demonstrative batch after Rule 107 material-culture lexicon. SOURCE CONTROLS: Patz §3.7 Tables "
    "3.12-3.14, exx.29, 90, 138-143, 293-295, 509, 583, 626-627, 636, and source narrative lines. PROCESS STORAGE: "
    "source pass, Yalanji/Nyungkul dialect controls, duplicate preflight, lint outputs, five-lens review, close, export, "
    "and live-doc verification are stored in process_events and the batch process log."
)

LESSONS = [
    ("morphology", "Use Yalanji root forms yanyu 'this/these' and yaluy 'here'; Nyungkul yanya/yalay are source contrasts, not the default corpus forms.", "Rule 108: Yalanji demonstrative dialect guard."),
    ("morphology", "Demonstrative pronouns case-mark like nominals and can co-occur with nouns in the same case: yalu-ngku jalbu-ngku, yinya-ngka kaya-ngka, yinyay-anka karrkay-anka.", "Rule 108: demonstrative case agreement."),
    ("morphology", "The 'this' paradigm is suppletive: yanyu ABS, yalu-/yaluy- in ERG/DAT/LOC/POSS, and yala- in ABL/ABESS/COMIT.", "Rule 108: this-paradigm suppletion."),
    ("morphology", "The 'that' paradigm uses yinya ABS, yinya-ngka ERG:pt, yinyay-anka DAT:pt, yinyay-anda LOC:pt, yinya-muny ABL, yinya-mundu ABESS, and yinya-nji COMIT.", "Rule 108: that-paradigm case forms."),
    ("syntax", "Local demonstratives yaluy/yinyay stand as local words, not as ordinary modifiers inside a larger NP; 'on that rock' is preferably paraphrased as 'there, rock-LOC'.", "Rule 108: local demonstrative syntax."),
    ("morphology", "Patz says Yalanji often rejects neutral LOC yaluymbu in favor of the local demonstrative yaluy; Batch 150 therefore avoids yaluymbu.", "Rule 108: yaluymbu avoidance."),
    ("morphology", "Human plural demonstratives yalu-rriny and yinya-rriny are human-reference forms and apparently ABS only; do not case-mark them in new rows without a new source.", "Rule 108: -rriny restriction."),
    ("morphology", "Local demonstratives take -arra for inhabitants: yaluy-arra, yinyay-arra; these can inflect in normal nominal case patterns.", "Rule 108: local -arra inhabitants."),
    ("morphology", "wawu- with a demonstrative must attach to an ablative form: wawu-yinya-muny, wawu-yala-muny. Do not use wawu- with bare yinya/yanyu.", "Rule 108: wawu plus ablative."),
    ("syntax", "Demonstrative yanyu can introduce a new salient participant; yinya reintroduces or maintains a known salient participant in narrative.", "Rule 108: narrative demonstrative function."),
    ("lexicon", "kaban is paper/book in the dictionary; source ex.140 translates it as letter. Batch 150 English uses paper to stay inside dictionary scope.", "Rule 108: kaban gloss restraint."),
    ("register", "Abessive demonstrative forms yalamundu/yinyamundu are table-sourced but not example-rich; keep them sparse and low-confidence until an elder/source check expands them.", "Rule 108: abessive caution."),
    ("orthography", "Legitimate word-final -rriny remains allowed for plural demonstratives; do not mistake it for verbal past -ny leakage.", "Rule 108: -rriny orthography."),
    ("process", "Exact duplicate preflight is essential for demonstratives because many Patz source rows were already accepted in Rule 47 and later batches.", "Rule 108: duplicate preflight."),
]

LEXEMES = [
    ("yanyu", "demonstrative", None, "ABS", "this; these", "batch-150: Yalanji ABS demonstrative pronoun."),
    ("yinya", "demonstrative", None, "ABS", "that; those", "batch-150: demonstrative pronoun in apposition and nominal sentences."),
    ("yalungku", "demonstrative", None, "ERG:pt", "this, ergative potent", "batch-150: case-agreeing this-ERG:pt with human A nouns."),
    ("yinyangka", "demonstrative", None, "ERG:pt", "that, ergative potent", "batch-150: case-agreeing that-ERG:pt."),
    ("yaluyngku", "demonstrative", None, "DAT", "this, dative", "batch-150: grammar Table 3.13 this-DAT."),
    ("yinyayngka", "demonstrative", None, "DAT", "that, dative", "batch-150: grammar Table 3.13 that-DAT."),
    ("yaluyunku", "demonstrative", None, "DAT:pt", "this, dative potent", "batch-150: grammar Table 3.13 this-DAT:pt."),
    ("yinyayanka", "demonstrative", None, "DAT:pt", "that, dative potent", "batch-150: Patz ex.139 that child search frame."),
    ("yaluyundu", "demonstrative", None, "LOC:pt", "this, locative potent", "batch-150: grammar Table 3.13 this-LOC:pt."),
    ("yinyayanda", "demonstrative", None, "LOC:pt", "that, locative potent", "batch-150: Patz ex.140 give to that one."),
    ("yalamuny", "demonstrative", None, "ABL", "from this", "batch-150: this-ABL and wawu-yala-muny."),
    ("yinyamuny", "demonstrative", None, "ABL", "from that; from there", "batch-150: that/there ABL rows."),
    ("yalamundu", "demonstrative", None, "ABESS", "without this one", "batch-150: table-sourced abessive, low-confidence usage."),
    ("yinyamundu", "demonstrative", None, "ABESS", "without that one", "batch-150: table-sourced abessive, low-confidence usage."),
    ("yalanji", "demonstrative", None, "COMIT", "with this", "batch-150: this-COMIT; also transparent in language name."),
    ("yinyanji", "demonstrative", None, "COMIT", "with that", "batch-150: that-COMIT from Patz ex.90 and Table 3.13."),
    ("yalumbu", "demonstrative", None, "POSS", "this one's", "batch-150: Table 3.13 POSS zero-infl this."),
    ("yinyamba", "demonstrative", None, "POSS/LOC", "that one's; at/in that", "batch-150: possessive sense selected in a bag row."),
    ("yaluy", "demonstrative-local", None, "LOC", "here; this place", "batch-150: local demonstrative here."),
    ("yinyay", "demonstrative-local", None, "LOC", "there", "batch-150: local demonstrative there."),
    ("yinyaymba", "demonstrative-local", None, "LOC", "there, locative", "batch-150: Patz ex.142-143 local demonstrative locative."),
    ("yaluymuny", "demonstrative-local", None, "ABL", "from here", "batch-150: Patz ex.141 local demonstrative ablative."),
    ("yalurriny", "demonstrative", None, "ABS-human-pl", "these people", "batch-150: human plural demonstrative ABS only."),
    ("yinyarriny", "demonstrative", None, "ABS-human-pl", "those people", "batch-150: human plural demonstrative ABS only."),
    ("yaluy-arra", "noun", None, "inhabitant", "people of this place", "batch-150: local demonstrative plus -arra inhabitants."),
    ("yinyay-arra", "noun", None, "inhabitant", "people of that place", "batch-150: local demonstrative plus -arra inhabitants."),
    ("wawu-yinya-muny", "temporal-adverbial", None, "TEMP4+ABL", "after/since that", "batch-150: Patz ex.636."),
    ("wawu-yala-muny", "temporal-adverbial", None, "TEMP4+ABL", "after/since this", "batch-150: wawu- plus this-ABL."),
    ("kaban", "noun", None, "NA", "paper; book", "batch-150: source ex.140 translates as letter; dictionary scope kept as paper/book."),
]


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}")

    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-150-verify", note, 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 108 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to Yalanji-vs-Nyungkul forms, case agreement, suppletive bases, local-vs-pronoun "
            "demonstratives, yaluymbu avoidance, -rriny ABS-only restriction, -arra inhabitants, wawu-ABL, abessive "
            "low-confidence forms, and exact duplicate avoidance."
        ),
        artifact_path="process_logs/batch-150-demonstratives-process.md",
        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 150: 50 accepted Rule 108 demonstrative/deictic rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_150.py",
        artifact_path="batch_scripts/close_150.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]
    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='batch-150-verify'").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, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, "
        f"{process_events} process events, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
