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

NOTES = (
    "CONSTRUCTION: DIRECT SPEECH, REPORTING CLAUSES, AND QUOTATION FRAMES (Rule 100). 50 rows. DESIGN: a "
    "construction batch after Rule 99 lexical work, deliberately distinct from the question-heavy Rule 66/Batch 108. "
    "COVERED: balka-l with LOC:pt addressees before direct quotes; yalama-l direct-quote reporting; babaji-y with "
    "ABS/S actor and LOC:pt person asked before quoted questions; short yuwu/kari/yalada quoted replies; yirrka-y "
    "cry-out frames with LOC addressees; kunja-l call/summon frames; and medial report clauses where a quote precedes "
    "the reporting verb and quote continuation follows it. SOURCE CONTROLS: appendix-text extraction rows for "
    "yinduy-nju yalama-ny, Wulbuman-angka balka-ny, medial Bunda-y ... yalama-ny ... yubal..., quote-only Kari/Yuwu, "
    "yirrka-nya nganjan-anda ngamu-ndu, Jana kunja-nya, Ngayu Chris-anda balka-ny, and Chris-anda babaji-ny; living "
    "book rules for balka-l LOC:pt addressee and fixed-intransitive babaji-y actor case. PROCESS STORAGE: source-pass, "
    "scope-control, banking, lint, review, and close evidence recorded in process_events. CORRECTIONS BEFORE CLOSE: "
    "none to Kuku surfaces; manual review accepted all 50 rows as banked. Pre-close lint scanned 7197 rows with 0 "
    "issues; verified metric remained 7147 before close because the batch was under_review."
)

LESSONS = [
    ("syntax", "Direct speech is punctuation plus report framing: REPORTING_CLAUSE: \"QUOTE\"; do not insert an English-style complementizer.", "cheatsheet Rule 100: direct quotation frame."),
    ("syntax", "`balka-l` 'say/tell to someone' keeps the addressee in LOC:pt in this corpus (`karrkay-anda`, `ngamu-ndu`, `dingkar-anda`).", "cheatsheet Rule 100: balka-l addressee case."),
    ("syntax", "`babaji-y` remains fixed-intransitive: actor ABS/S, person asked LOC, topic DAT if present, direct question after a colon.", "cheatsheet Rule 100: babaji-y direct question frame."),
    ("lexicon", "`yalama-l` is licensed here only as 'say/do' reporting; it is not an answer, wait, or obey verb.", "dictionary errata Batch-142: yalama-l guard."),
    ("syntax", "`yirrka-y` cry-out rows keep the actor ABS/S and addressee LOC:pt.", "cheatsheet Rule 100: yirrka-y call-out frame."),
    ("syntax", "`kunja-l` call/summon rows differ from `balka-l`: A may be ERG and the called person/animal is the object, followed by the direct quote.", "cheatsheet Rule 100: kunja-l call frame."),
    ("discourse", "Short quoted replies can be just `yuwu`, `kari`, or `yalada`; do not create a separate answer lexeme.", "dictionary errata Batch-142: short replies."),
    ("orthography", "Medial reporting rows may start with a quote; bank scripts and lint strip leading quotes for capitalization checks.", "operator guide Rule 100 process note."),
    ("scope", "Quoted questions in Rule 100 are subordinate to the reporting-frame goal; Rule 66 remains the main interrogative inventory.", "operator guide next-batch scope note."),
    ("orthography", "Authored bare past surfaces continue to normalize source `-ny` to surface `-n` unless the older source shape is embedded in a larger accepted form like `kada-ny-baja`.", "dictionary errata Batch-142: past surface convention."),
    ("syntax", "Question-response pairings should keep cases independent across clauses: `babaji-y` actor ABS in the question clause, but ERG speaker is possible in a separate `balka-l` reply clause.", "cheatsheet Rule 100: Q/A case separation."),
    ("fidelity", "Do not mine generated model or Bible output as authority for synthetic Kuku content; source authority for this batch is Patz/dictionary/living-book evidence.", "operator guide Rule 100 source authority note."),
    ("syntax", "A bare absolutive human after `balka-l` is avoided in 'say to' rows because it risks the 'make' sense; use LOC:pt for the addressee.", "cheatsheet Rule 100: avoid bare ABS addressee with balka-l."),
    ("discourse", "One-word direct quotes are useful and source-shaped; they test quotation punctuation without forcing extra lexical material.", "sample pages Rule 100 direct-speech note."),
    ("process", "Continue storing source pass, scope decisions, lint, review, close, export, and live-doc verification in process_events for every future batch.", "operator guide Rule 100 process ledger continuation."),
]

LEXEMES = [
    ("balkal", "verb-tr", "l", "NA", "say; tell; speak", "batch-142: direct-speech reporting verb; addressee LOC:pt when 'say to'."),
    ("yalamal", "verb", "l", "NA", "say; do", "batch-142: reporting verb only; not answer/wait/obey."),
    ("babaji", "verb-intr", "y", "NA", "ask", "batch-142: fixed-intransitive ask frame with ABS actor and LOC person asked."),
    ("yirrkay", "verb-intr", "y", "NA", "shout; cry out; call", "batch-142: cry-out frame with LOC addressee."),
    ("kunjal", "verb-tr", "l", "NA", "call; summon; invite", "batch-142: transitive call frame before direct quote."),
    ("yuwu", "particle", None, "NA", "yes", "batch-142: short quoted reply."),
    ("kari", "particle", None, "NA", "no; not", "batch-142: short quoted reply and prohibitive quote material."),
    ("yalada", "particle", None, "NA", "alright; that's settled", "batch-142: quoted discourse reply."),
    ("bunday", "verb-intr", "y", "NA", "sit; stay", "batch-142: quoted imperative Bunda-y."),
    ("dungay", "verb-intr", "y", "NA", "go", "batch-142: quoted imperative Dunga-y."),
    ("kaday", "verb-intr", "y", "NA", "come", "batch-142: quoted imperative and direct-question content."),
    ("nukal", "verb-tr", "l", "NA", "eat", "batch-142: quoted imperative nuka."),
    ("dakal", "verb-intr", "l", "NA", "climb", "batch-142: source quoted question Ngali daka-l."),
    ("juwal", "noun", None, "neutral", "digging stick", "batch-142: source quoted instrument juwal-da."),
    ("damal", "verb-tr", "l", "NA", "spear", "batch-142: source quoted imperative dama."),
    ("manyarr", "noun", None, "neutral", "wife", "batch-142: source wives + yalama-ny quote frame."),
    ("wulbuman", "noun", None, "neutral", "old woman", "batch-142: source Wulbuman-angka balka-ny quote frame."),
    ("yinduy", "numeral/pronoun", None, "neutral", "one; one person", "batch-142: source yinduy-nju yalama-ny quote frame."),
    ("wanyu-nguy", "interrogative", None, "NA", "what kind", "batch-142: quoted question content only."),
]


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-142-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 100 rows: morphology, lexicon, syntax, fidelity, and register.",
        artifact_path="process_logs/batch-142-direct-speech-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 142: 50 accepted direct-speech/reporting rows, five-lens reviews, lessons, lexeme logs, and process evidence stored.",
        command="python3 batch_scripts/close_142.py",
        artifact_path="batch_scripts/close_142.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-142-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())
