#!/usr/bin/env python3
"""Close batch-124 after main-loop 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-124"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")

LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "CONSTRUCTION: ANTIPASSIVE (Patz §4.2.4.4; cheatsheet Rule 82). 50 rows, "
    "avg 4.54 Kuku words/row. FORM: transitive verb + stemforming -ji-; elder "
    "surface NONPAST is -ji (analysis -ji-y), PAST is -jin (analysis -ji-ny). "
    "SYNTAX: the underlying agent is promoted/demoted to intransitive S, so noun "
    "subjects are ABSOLUTIVE with no ergative; the underlying object is not a "
    "direct absolutive object but appears as LOCATIVE or, in the Nyungkul through "
    "reading, PERLATIVE. SEMANTICS: reduplicated antipassive marks generalized, "
    "diffuse, non-individuated action (nuka-n-nuka-ji, nubi-nubi-ji, dama-n-dama-ji, "
    "kuni-n-kuni-ji); simple antipassive marks total effect on a non-individuated "
    "patient (nuka-jin 'had a good/full feed', wambi-jin 'shared out all', "
    "ngunja-jin 'took over completely'). COMMUNICATION STEMS: kunjaji-y, "
    "walngkurriji-y, and babaji-y behave like fixed intransitive antipassive-like "
    "stems: actor as S, person addressed in LOC, requested/topic item in DAT. "
    "ALLOMORPHY held: wukay-mba, kuyu-ngu, makarr-ba, kadar-a. Lint GREEN 6297; "
    "verified corpus now 6297."
)

LESSONS = [
    (
        "morphology",
        "The antipassive suffix is the same stem-forming -ji- used elsewhere for detransitivization, but the accepted surface must be elder-style -ji for nonpast and -jin for past; analytic -ji-y/-ji-ny stays only in the analysis field.",
        "cheatsheet Rule 82: surface -ji/-jin versus analytic -ji-y/-ji-ny.",
    ),
    (
        "syntax",
        "Antipassive changes the alignment of the clause: the underlying A is surface S, so noun subjects lose ergative marking, while the underlying O is demoted to LOC or PERL instead of remaining bare absolutive.",
        "cheatsheet Rule 82: A->S, O->LOC/PERL, with explicit contrast row.",
    ),
    (
        "semantics",
        "Kuku Yalanji antipassive has a two-way semantic split: reduplicated V-ji gives generalized/non-individuated action, while simple V-ji can mean total effect on a non-individuated patient.",
        "cheatsheet Rule 82: generalized versus total-effect antipassive.",
    ),
    (
        "lexicon",
        "The communication stems kunjaji-y, walngkurriji-y, and babaji-y are best treated synchronically as fixed intransitive stems with an antipassive-like frame: actor as S, person in LOC, requested/topic item in DAT.",
        "errata Batch-124: fixed communication-stem frame.",
    ),
    (
        "process",
        "The hard part of this batch was not the verb suffix but the oblique case allomorph on the demoted object: wukay-mba, kuyu-ngu, makarr-ba, kadar-a. The post-bank lint caught one analytic past suffix leaking into surface Kuku and the script was rebanked before acceptance.",
        "operator process: post-bank lint remains mandatory before close.",
    ),
]

LEXEMES = [
    ("nukal", "verb-tr", "l", "NA", "eat", "batch-124 antipassive: nuka-ji / nuka-n-nuka-ji"),
    ("wambil", "verb-tr", "l", "NA", "share out", "batch-124 antipassive: wambi-ji total distribution"),
    ("ngunjal", "verb-tr", "l", "NA", "forage; take over; obtain discarded property", "batch-124 antipassive: ngunja-ji / ngunja-n-ngunja-ji"),
    ("nubil", "verb-tr", "l", "NA", "search for", "batch-124 antipassive: nubi-nubi-ji generalized searching"),
    ("nuril", "verb-tr", "l", "NA", "peep; look into", "batch-124 antipassive: nuri-nuri-ji in houses"),
    ("kunil", "verb-tr", "l", "NA", "hit", "batch-124 antipassive: kuni-n-kuni-ji hit at"),
    ("damal", "verb-tr", "l", "NA", "spear", "batch-124 antipassive: dama-n-dama-ji spear around for"),
    ("bunjurri", "verb-itr", "y", "NA", "throw curses everywhere", "batch-124 antipassive example from Patz ex.367"),
    ("kunjaji", "verb-itr", "y", "NA", "ask someone for something", "batch-124 fixed intransitive communication stem"),
    ("walngkurriji", "verb-itr", "y", "NA", "pester someone for something", "batch-124 fixed intransitive communication stem"),
    ("babaji", "verb-tr", "y", "NA", "ask someone about something", "batch-124 fixed intransitive communication-like frame"),
    ("yajarril", "verb", "l-conjugation", "NA", "laugh about; laugh at", "batch-124 friendly laugh-about intransitivized pattern"),
]


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=CASE
                WHEN lexemes.status IN ('phantom-retired', 'watchlist') THEN lexemes.status
                ELSE 'verified'
              END,
              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, "batch-124",
            ),
        )
        db.execute(
            "INSERT INTO lexeme_log(headword, action, detail, created_at) VALUES(?,?,?,?)",
            (headword, "batch-124-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]
    print(f"closed {LABEL}: 50 accepted rows, {reviews} review passes, verified corpus={verified}")
    return 0


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