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

NOTES = (
    "CONSTRUCTION: MANNER ADVERBS, ADVERBIAL -KU, AND QUALITY-TO-MANNER FRAMES (Rule 106). 50 rows. DESIGN: "
    "high-control construction batch after Rule 105 lexical human-quality work. SOURCE CONTROLS: Patz §3.8.6.1 "
    "adverbial particles; §3.8.6.2 derived adverbs; §4.1.2 one-modifier verb-complex limit; exx.192-203; ex.445; "
    "ex.512; narrative yala-ku/junkay-ku lines. PROCESS STORAGE: source pass, duplicate preflight, grammar-only "
    "homograph warnings, risk controls, lint outputs, five-lens review, close, export, and live-doc verification are "
    "stored in process_events and the batch process log."
)

LESSONS = [
    ("syntax", "Verb complexes in this batch carry only one modifier; Patz says verb complexes with more than one modifier are not attested.", "Rule 106: verb-complex modifier limit."),
    ("syntax", "Adverbial particles are non-inflecting; they may stand before or after the verb, with preferred position immediately near it.", "Rule 106: adverbial-particle placement."),
    ("morphology", "Some adverbial particles may take optional manner -ku, but they remain particles, not adjectives in noun phrases.", "Rule 106: particle versus adjective distinction."),
    ("morphology", "Derived adverbs form by adjective + -ku, reduplication, or reduplication + -ku; the third pattern is rare and used sparingly.", "Rule 106: derived adverb patterns."),
    ("morphology", "With comitative and privative stems, reduplication is not favoured; safe rows include kuli-ji-ku and kiru-kari-ku.", "Rule 106: comitative/privative adverbs."),
    ("morphology", "In transitive clauses with simple adjectives, use neutral ERG/INST before -ku: jinbal-da-ku and mumbar-abu-ku.", "Rule 106: transitive inflected adverbs."),
    ("syntax", "Do not generalize buyun-ku or ngulkurr-ku into every transitive frame; simple-adjective transitive adverbs need a fresh source or the inflected pattern.", "Rule 106: transitive adverb caution."),
    ("lexicon", "Grammar-sourced ngambuy means fittingly/appropriately in §3.8.6.1, despite the dictionary homograph's strong-taste entry.", "Rule 106: ngambuy homograph."),
    ("lexicon", "Grammar-sourced jangka is upright/straight as a posture particle; the dictionary also has unrelated jangka noun senses.", "Rule 106: jangka homograph."),
    ("lexicon", "wadu(wadu) is the Patz off-course/astray direction particle; dictionary wadu wrong/incorrect is related but not a free English 'wrongly' adverb license.", "Rule 106: wadu scope."),
    ("lexicon", "ngura in this batch is too-soon/impatient manner, not a generic speed adverb replacing jinbal-ku.", "Rule 106: ngura scope."),
    ("morphology", "yala-ku is the source form for like this; do not duplicate the already accepted Yala-ku balka row.", "Rule 106: yala-ku."),
    ("morphology", "Temporal nominal -ku rows such as warru-ku and karrkay-nyja-ku remain marked as potentially adverbial/emphatic ambiguous, as Patz cautions.", "Rule 106: temporal nominal -ku caution."),
    ("orthography", "Cook/burn past remains wajun; turtle remains ngawiya. These guards carry forward even in an adverb batch.", "Rule 106: carried orthographic guards."),
]

LEXEMES = [
    ("nguymal", "particle", None, "NA", "thoroughly; truly", "batch-148: adverbial particle; optional -ku in Patz ex.192."),
    ("nganjarr-nganjarr", "particle", None, "NA", "discreetly; with hidden purpose", "batch-148: reduplicated adverbial particle; corpus surface hyphenates reduplication."),
    ("ngambuy", "particle", None, "NA", "fittingly; appropriately", "batch-148: grammar-sourced adverbial-particle sense, not dictionary strong-taste sense."),
    ("nguyarr", "particle", None, "NA", "not quite", "batch-148: partial-action adverbial particle."),
    ("kanban", "adverb", None, "NA", "by mistake", "batch-148: accidental-action adverb."),
    ("jururr", "particle", None, "NA", "repeatedly; one after another with motion verbs", "batch-148: sequence adverbial particle."),
    ("nganga", "adverb", None, "NA", "briefly; just a little bit; only", "batch-148: brief-action particle."),
    ("wudu", "particle", None, "NA", "absorbed in an activity", "batch-148: grammar-sourced manner particle."),
    ("walku", "adverb", None, "NA", "right past", "batch-148: direction particle with dunga-y."),
    ("maku", "locational", None, "NA", "towards; straight towards", "batch-148: direction particle."),
    ("wadu", "adverb", None, "NA", "astray; off course", "batch-148: Patz wadu(wadu) direction-particle sense."),
    ("mingki", "particle", None, "NA", "crouching; squatting", "batch-148: posture particle from Patz."),
    ("jarrbarr", "particle", None, "NA", "prone; on stomach", "batch-148: posture particle from Patz."),
    ("jangka", "particle", None, "NA", "upright; straight", "batch-148: posture particle from Patz; homograph warning."),
    ("ngura", "adverb", None, "NA", "too soon; impatiently", "batch-148: manner particle."),
    ("yarngkay", "particle", None, "NA", "secretly", "batch-148: grammar-sourced manner particle."),
    ("murruji", "adverb", None, "NA", "cannot", "batch-148: adverbial particle."),
    ("jinbal-ku", "adverb", None, "NA", "quickly; fast", "batch-148: derived adverb from jinbal."),
    ("jinbal-jinbal", "adverb", None, "NA", "quickly; fast, reduplicated", "batch-148: derived reduplicated adverb."),
    ("waymbul-ku", "adverb", None, "NA", "slowly; gently", "batch-148: derived adverb from waymbul."),
    ("mumbar-ku", "adverb", None, "NA", "neatly; firmly", "batch-148: intransitive derived adverb."),
    ("kuli-ji-ku", "adverb", None, "NA", "angrily; viciously; wildly", "batch-148: comitative-stem adverb."),
    ("kiru-kari-ku", "adverb", None, "NA", "stupidly; foolishly", "batch-148: privative-stem adverb."),
    ("jinbal-da-ku", "adverb", None, "NA", "quickly in transitive clauses", "batch-148: simple adjective + neutral ERG/INST + -ku."),
    ("mumbar-abu-ku", "adverb", None, "NA", "carefully; neatly in transitive clauses", "batch-148: simple adjective + neutral ERG/INST + -ku."),
    ("yala-ku", "adverb", None, "NA", "like this", "batch-148: demonstrative/comparison adverb."),
    ("warru-ku", "temporal-adverbial", None, "NA", "as a young man", "batch-148: temporal nominal -ku, marked ambiguous with emphatic -ku."),
    ("karrkay-nyja-ku", "temporal-adverbial", None, "NA", "as a child", "batch-148: inflected temporal nominal -ku in transitive frame."),
    ("wanjarr-ku", "interrogative-adverb", None, "NA", "how", "batch-148: wanjarr usually takes adverbial -ku."),
]


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-148-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 106 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to the one-modifier verb-complex limit, particle/adjective distinction, optional -ku, "
            "reduplication rarity, transitive jinbal-da-ku/mumbar-abu-ku, comitative/privative adverbs, grammar-only "
            "homographs ngambuy/jangka, wadu scope, yala-ku duplicates, temporal -ku ambiguity, and carried orthographic guards."
        ),
        artifact_path="process_logs/batch-148-manner-adverbs-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 148: 50 accepted Rule 106 manner-adverb rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_148.py",
        artifact_path="batch_scripts/close_148.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-148-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())
