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

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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

NOTES = (
    "CONSTRUCTION: PERCEPTION/COGNITION COMPLEMENT AND SIMULTANEOUS-CLAUSE FRAMES (Rule 98). 50 rows. DESIGN: "
    "reuse Rule 97 perception/cognition lexicon but shift the grammatical target to Patz-backed clause structures: "
    "simultaneous verb + -nyV clauses under perception verbs; whole-event perception with retained subordinate A/S; "
    "oblique and -mun-bu/-mun-du simultaneous complexes; wawu/binal/babal/memory purposive complements; directive "
    "balka-l/kunja-l plus PURP; and fixed intransitive communication stems babaji-y, kunjaji-y, walngkurriji-y with "
    "LOC person and DAT topic/requested item. SOURCE CONTROLS: Patz 4.4.4.1 ex.457-467, Patz 4.4.5 ex.506-507, "
    "Patz 4.9.1 ex.584-590, Patz 4.4.1 ex.414-415, Patz 4.2.4.4 ex.376-378. CORRECTIONS BEFORE CLOSE: duplicate "
    "guard forced four participant variants; lint corrected surface warri-y -> warri in rows 22/24; manual syntax "
    "review corrected babaji-y actors from ERG to ABS in rows 47/48; manual lexicon review replaced weaker jaba-l "
    "weave wording with source-backed balji wukurri-l-wukurri-nya in row 5. Pre-close lint scanned 7097 rows with "
    "0 issues; verified metric remained 7047 before close."
)

LESSONS = [
    ("syntax", "Simultaneous `-nyV` clauses are primarily temporal; do not use them as free English relative clauses.", "cheatsheet Rule 98: simultaneous `-nyV`."),
    ("morphology", "In reduplicated l-conjugation simultaneous verbs, retain the `-l` inside the copy: `baka-l-baka-nya`, `wukurri-l-wukurri-nya`.", "cheatsheet Rule 98: reduplication surface."),
    ("syntax", "Perception verbs can take a whole subordinate event as object with the main object omitted and subordinate A/S retained.", "cheatsheet Rule 98: whole-event perception."),
    ("syntax", "The oblique simultaneous examples allow `verb-nya-mun-bu` locative subordinate complexes, but this is source-shaped and should not be generalized freely.", "cheatsheet Rule 98: `-mun-bu` complexes."),
    ("syntax", "Same-actor simultaneous clauses can show case agreement such as `janjana-nya-mun-du` in the Patz ex.507 frame.", "cheatsheet Rule 98: same-actor agreement."),
    ("morphology", "`warri-y` surfaces as `warri`; lint caught draft `warriy` in rows 22/24 before close.", "dictionary errata Batch-140: y-deletion."),
    ("syntax", "`babaji-y`, `kunjaji-y`, and `walngkurriji-y` are fixed intransitive stems: actor is S/ABS, person addressed is LOC, topic/request is DAT.", "cheatsheet Rule 98: fixed communication stems."),
    ("syntax", "`balka-l` directive addressee is DATIVE and the commanded action is a PURP complement.", "cheatsheet Rule 98: directive frame."),
    ("syntax", "`wawu` and `binal` take dative nouns or purposive verbs as complements; the main predicate remains intransitive.", "cheatsheet Rule 98: particle predicates."),
    ("morphology", "`binal-kari` is the privative not-know form and governs a DAT noun such as `kuku-ku`.", "cheatsheet Rule 98: binal-kari."),
    ("lexicon", "For dillybag weaving, prefer source-backed `balji wukurri-l` over weaker or uncertain weave wording.", "dictionary errata Batch-140: weaving row correction."),
    ("process", "Duplicate checking is part of linguistic review; four source-shaped rows were varied before any DB write.", "operator guide: duplicate guard."),
]

LEXEMES = [
    ("nyajil", "verb-tr", "l", "NA", "see; hear; perceive", "batch-140: perception main verb governing simultaneous subordinate clauses."),
    ("baka-l-baka-nya", "construction", None, "NA", "digging, simultaneous subordinate", "batch-140: reduplicated l-conjugation SUB pattern."),
    ("dama-l-dama-nya", "construction", None, "NA", "spearing, simultaneous subordinate", "batch-140: reduplicated l-conjugation SUB pattern."),
    ("nuka-nuka-ji-nya", "construction", None, "NA", "feeding, simultaneous intransitivized subordinate", "batch-140: Patz ex.461 frame."),
    ("wulji-l-wulji-nya", "construction", None, "NA", "bailing out, simultaneous subordinate", "batch-140: Patz ex.506 bailing-water frame."),
    ("wukurri-l-wukurri-nya", "construction", None, "NA", "weaving/following, simultaneous subordinate", "batch-140: source-backed dillybag weaving correction."),
    ("warri", "verb-intr", "y", "NA", "run (surface nonpast)", "batch-140: surface of warri-y after final-y deletion."),
    ("bundanda-nya-mun-bu", "construction", None, "neutral", "sitting subordinate locative complex", "batch-140: Patz ex.466b frame."),
    ("janjana-nya-mun-du", "construction", None, "neutral", "standing subordinate ergative complex", "batch-140: Patz ex.507 frame."),
    ("binal", "particle", None, "NA", "know; know how", "batch-140: binal plus purposive complement."),
    ("binal-kari", "adjective", None, "NA", "not know", "batch-140: not-know plus DAT noun."),
    ("wawu", "particle", None, "NA", "want; like", "batch-140: wawu plus PURP complement."),
    ("babal", "verb-tr", "l", "NA", "try; taste", "batch-140: conative plus PURP complement."),
    ("milka-wulay", "verb-intr", "y", "NA", "forget", "batch-140: forget plus PURP complement."),
    ("binalku", "particle", None, "NA", "remember", "batch-140: remember plus PURP complement."),
    ("binal-bungal", "verb-tr", "l", "NA", "teach", "batch-140: teach plus PURP complement."),
    ("kunjaji", "verb-intr", "y", "NA", "ask someone for something", "batch-140: fixed intransitive LOC/DAT frame."),
    ("walngkurriji", "verb-intr", "y", "NA", "pester someone for something", "batch-140: fixed intransitive LOC/DAT frame."),
    ("babaji", "verb-intr", "y", "NA", "ask someone about something", "batch-140: fixed intransitive LOC/DAT frame."),
    ("balkal", "verb-tr", "l", "NA", "say; tell; make", "batch-140: directive addressee DAT plus PURP frame."),
]


def main() -> int:
    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("BEGIN")
    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-140-verify", note, 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))
    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-140-verify'").fetchone()[0]
    print(
        f"closed {LABEL}: 50 accepted rows, {reviews} review passes, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, verified corpus={verified}"
    )
    return 0


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