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

NOTES = (
    "CONSTRUCTION: PRECAUTIONARY, SUCCESSIVE, AND PRIOR-EVENT TIMING CONTRASTS (Rule 114). 50 rows. DESIGN: "
    "hand-authored rows contrasting -nyji PRECAUT preventable bad outcome, -nyjiku SUCC following-event timing, "
    "and wawu-...-muny TEMP4 prior completed event. SOURCE CONTROLS: Patz 3.8.4.2, 4.4.2, 4.4.3, 4.4.4.3, and "
    "3.10.1; duplicate-surface scan against existing -nyji/-nyjiku/wawu rows; under-review lint caught and fixed "
    "three elder-surface -iy forms before close. PROCESS STORAGE: source pass, existing-surface scan, lint failure, "
    "surface-fix rebank, five-lens review, close, lint, export, and live-doc verification are stored."
)

LESSONS = [
    ("syntax", "Precautionary -nyji states an undesirable event that the main clause action prevents; it is not a generic future or maybe.", "Rule 114: -nyji precautionary."),
    ("syntax", "A precautionary clause normally follows the main clause, and explicit A/O retention is safer when deletion could obscure who harms whom.", "Rule 114: precautionary participant retention."),
    ("fidelity", "Translate -nyji rows with 'lest' or 'so X does not happen', not with ordinary 'before'.", "Rule 114: precautionary English."),
    ("syntax", "Successive -nyjiku marks the following event as the timing reference: the main clause happens shortly before it.", "Rule 114: -nyjiku successive."),
    ("fidelity", "Translate -nyjiku rows as 'before X happens'; do not treat them as preventable bad outcomes unless context independently supplies danger.", "Rule 114: successive English."),
    ("syntax", "Patz says successive constructions are not especially frequent; use them deliberately for construction teaching rather than where a topic chain would be more natural.", "Rule 114: successive sparseness."),
    ("syntax", "When successive clauses have different core roles, pronoun reduction/retention is preferred over over-deletion.", "Rule 114: successive coreference."),
    ("morphology", "Prior event uses TEMP4 wawu- plus an ablative -muny form; no wawu prior-event row is complete without ablative marking.", "Rule 114: wawu plus ablative."),
    ("syntax", "For prior events, Patz lets verb + -nya-muny express completed prior action only in restricted co-reference environments.", "Rule 114: verb prior event."),
    ("syntax", "If an event can be expressed by a noun, the noun attracts the ablative: use wawu-ngangkurr-muny or wawu-jilba-muny rather than forcing a verb + -nya-muny form.", "Rule 114: nominal prior event."),
    ("syntax", "Wawu-yinya-muny is the safe general 'after that' device when the co-reference shape would make a subordinate prior-event clause unclear.", "Rule 114: after-that fallback."),
    ("morphology", "Kuku elder surface drops word-final -y after i; Patz analysis may keep -y for forms such as nguju-wuri-y, julurri-ji-y, and banbadi-y.", "Rule 114: -iy surface drop."),
    ("lexicon", "Construction batches still need content-word checks: janji-l, bujil-janji-l, dara-y, wala-l, jarrakulba-l, banbadi-y, nguju-wuri-y, and ngangkurr were source-checked.", "Rule 114: lexeme checking."),
    ("fidelity", "Do not collapse Rule 112 kunka/nganganjirrka in-case clauses into Rule 114 -nyji; both are precaution-related but grammatically distinct.", "Rule 114: in-case contrast."),
    ("process", "The under-review rebank after lint was I3-safe because no Batch 156 rows had been accepted; accepted-row changes would require revisions rows.", "Rule 114: under-review rebank."),
    ("process", "Keep failed lint output in process_events; the -iy failure is evidence that the living phonology rule is actively protecting the corpus.", "Rule 114: process evidence."),
]

LEXEMES = [
    ("-nyji", "suffix", None, "verbal inflection", "precautionary; lest", "batch-156: preventable bad outcome construction."),
    ("-nyjiku", "suffix", None, "verbal inflection", "successive; before following event", "batch-156: following-event timing construction."),
    ("wawu-", "temporal-proclitic", None, "with ablative -muny", "after; since", "batch-156: prior-event TEMP4 construction."),
    ("janji-l", "verb", "l", "NONPAST janji-l", "bathe; swim", "batch-156: precautionary and prior-event bathing rows."),
    ("bujil-janji-nyji", "verb-form", None, "nose-bathe-PRECAUT", "drown; lest drown", "batch-156: Patz ex.432 source form."),
    ("nguju-wuri", "verb-form", None, "elder surface of nguju-wuri-y", "fool around; play for fun", "batch-156: Patz ex.433 surface after -iy drop."),
    ("kuni-nyji", "verb-form", None, "hit-PRECAUT", "lest hit", "batch-156: Patz ex.433 source form."),
    ("jikan", "noun", None, "LOC jikan-ba", "grass", "batch-156: long-grass snake-bite row."),
    ("bayka-nyji", "verb-form", None, "bite-PRECAUT", "lest bite", "batch-156: dog/snake/fish risk rows."),
    ("dara-y-mani-nyji", "verb-form", None, "fall-y-CAUS-PRECAUT", "lest drop it", "batch-156: Patz ex.441 source form."),
    ("dara-nyji", "verb-form", None, "fall-PRECAUT", "lest fall", "batch-156: bag/food fall warning."),
    ("buyun-dama-nyji", "verb-form", None, "bad-CAUS-PRECAUT", "lest spoil it", "batch-156: Patz ex.436 source form."),
    ("jarrakulba-l", "verb", "l", "NONPAST jarrakulba-l", "carry", "batch-156: Patz ex.439 carry-lest-cry frame."),
    ("banbadi", "verb-form", None, "elder surface of banbadi-y", "cry repeatedly", "batch-156: PRECAUT/SUCC source forms after -iy drop."),
    ("wala-l", "verb", "l", "SUB wala-nya", "enter", "batch-156: rain-enter precaution and prior-event entering rows."),
    ("dakuy-ma-nyji", "verb-form", None, "hungry-INCHO-PRECAUT", "lest get hungry", "batch-156: Patz ex.511 table form."),
    ("bambay-ma-nyji", "verb-form", None, "sick-INCHO-PRECAUT", "lest get sick", "batch-156: sickness precaution form."),
    ("bayka-nyjiku", "verb-form", None, "bite-SUCC", "before it bites", "batch-156: Patz ex.445 contrast with bayka-nyji."),
    ("jilba-dunga-nyjiku", "verb-form", None, "walk-go-SUCC", "before going for a walk", "batch-156: Patz ex.446 source form."),
    ("wandi-nyjiku", "verb-form", None, "wake/rise-SUCC", "before waking/rising", "batch-156: Patz ex.165 source form."),
    ("nuka-nyjiku", "verb-form", None, "eat-SUCC", "before eating", "batch-156: hand-washing row."),
    ("ngara-nyjiku", "verb-form", None, "set.up-SUCC", "before setting up camp", "batch-156: Patz ex.449 source form."),
    ("duda-nyjiku", "verb-form", None, "pound-SUCC", "before pounding", "batch-156: Patz ex.450 source form."),
    ("warri-nyjiku", "verb-form", None, "run-SUCC", "before it runs", "batch-156: Patz ex.453 source form."),
    ("dara-nyjiku", "verb-form", None, "fall-SUCC", "before rain falls", "batch-156: Patz ex.454 source form."),
    ("kada-nyjiku", "verb-form", None, "come-SUCC", "before it comes", "batch-156: pig/wind/children come rows."),
    ("wawu-janji-nya-muny", "verb-form", None, "TEMP4-bathe-SUB-ABL", "after bathing", "batch-156: Patz ex.491 source form."),
    ("wawu-wala-nya-muny", "verb-form", None, "TEMP4-enter-SUB-ABL", "after entering", "batch-156: Patz ex.492 source form."),
    ("wawu-bayka-nya-muny", "verb-form", None, "TEMP4-bite-SUB-ABL", "after biting", "batch-156: Patz ex.493 source form."),
    ("wawu-kambi-muny", "case-form", None, "TEMP4-clothes-ABL", "after washing clothes", "batch-156: Patz ex.494 object-ablative pattern."),
    ("wawu-kaya-muny", "case-form", None, "TEMP4-dog-ABL", "after feeding the dog", "batch-156: object-ablative pattern modeled on Patz ex.495."),
    ("wawu-jilba-muny", "case-form", None, "TEMP4-walk-ABL", "after the walk", "batch-156: Patz ex.497 preferred nominal prior event."),
    ("wawu-mayi-muny", "case-form", None, "TEMP4-food-ABL", "after the meal", "batch-156: Patz 3.10.1 source form."),
    ("wawu-yinya-muny", "case-form", None, "TEMP4-that-ABL", "after that", "batch-156: Patz 4.4.4.3 fallback sequence form."),
    ("wawu-ngangkurr-muny", "case-form", None, "TEMP4-barking.noise-ABL", "after barking", "batch-156: Patz ex.496 preferred noun form."),
    ("dikal", "noun", None, "ABS subject", "bird", "batch-156: rainbird successive source row."),
    ("ngangkurr", "noun", None, "ABL ngangkurr-muny", "barking noise", "batch-156: prior-event nominal source."),
]


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-156-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 114 rows. Morphology lens checked -nyji, -nyjiku, "
            "wawu-...-muny, past/nonpast surfaces, and -iy elder-surface corrections. Lexicon lens checked all new "
            "support roots and source-shaped forms. Syntax lens distinguished preventable bad outcome, following-event "
            "timing, and completed prior event. Fidelity lens checked English 'lest', 'before', and 'after' mappings. "
            "Register lens kept rows as practical fieldwork-style clauses pending elder verification."
        ),
        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 114 lessons covering -nyji/-nyjiku/wawu- contrasts, participant retention, nominal prior events, and -iy surface correction.",
        artifact_path="batch_scripts/close_156.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 114 construction forms and source-shaped examples.",
        artifact_path="batch_scripts/close_156.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 156: 50 accepted Rule 114 construction rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_156.py",
        artifact_path="batch_scripts/close_156.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='batch-156-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, under_review={under_review_remaining}, "
        f"verified corpus={verified}"
    )
    return 0


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