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

NOTES = (
    "LEXICAL: HUMAN QUALITIES, ABILITY, AND CHARACTER/STATE TERMS (Rule 105). 50 rows. DESIGN: follow the Rule 104 "
    "adjective construction batch with a source-bounded lexical batch for ability, competence, expert compounds, "
    "lazy/stupid/bossy/no-good qualities, truth/lie/confession/shame, contentment/agreement/willingness, tame/fierce, "
    "young/old, and tired. SOURCE CONTROLS: Patz adjectival particles binal/juburr; Patz mala- expert compounds; "
    "dictionary daki-daki/majarr; Patz/dictionary kiru-kari; Rule 99 truth/lie/shame inventory; dictionary minday, "
    "kuli-baka, wawu/wawurr terms, and baja-burray. PROCESS STORAGE: source pass, duplicate preflight, risk controls, "
    "row inventory, lint outputs, five-lens review, close, export, and live-doc verification are stored in process_events "
    "and the batch process log."
)

LESSONS = [
    ("lexicon", "Lazy is `daki-daki` or `majarr`; the stale spelling `manjarr` is not used in this batch.", "Rule 105: lazy/no-good-at-work lexicon."),
    ("lexicon", "`majarr` is lazy/no good for hunting or working and applies to both dogs and people.", "Rule 105: majarr scope."),
    ("lexicon", "`daki-daki` is lazy/in the way; source usage is `Yundu daki-daki, dungayda`.", "Rule 105: daki-daki source usage."),
    ("lexicon", "`kiru-kari` is brain-privative and means dull/stupid/silly; it can form `kiru-kari-ma-l` get stupid.", "Rule 105: kiru-kari."),
    ("morphology", "`mala-` attaches to noun roots for expert/good-at-X; use noun roots, not arbitrary verb stems.", "Rule 105: mala- expert compounds."),
    ("syntax", "`binal` and `juburr` are adjectival particles; they take dative noun complements or purposive verb complements.", "Rule 105: binal/juburr complements."),
    ("morphology", "`binal-bajaku` means know very much/exactly; `binal-kari` is the privative not-know form.", "Rule 105: binal degree and privative."),
    ("morphology", "`binal-ma-l` is learn; `binal-bunga-l` is teach.", "Rule 105: binal derivations."),
    ("lexicon", "`manubaja` truth, `jurril` lie/untruth, `warmbiji-y` lie/prevaricate, and `mala-yirrkay` confess/tell truth are distinct.", "Rule 105: truth/lie/confession split."),
    ("orthography", "Analysis may show y-conjugation final `-y`, but surfaces drop word-final `-iy`: `nguju-wuri`, not `nguju-wuriy`.", "Rule 105: final -iy surface discipline."),
    ("lexicon", "`milka-murruji` is ashamed/guilty; `murru-kaday` is become ashamed/shy; `murru-kaday-manil` shames someone.", "Rule 105: shame cluster."),
    ("lexicon", "`minday` includes tame, quiet, brave/not afraid/confident; keep it source-bounded and do not flatten to generic courage.", "Rule 105: minday scope."),
    ("lexicon", "`kuli-baka` is a person always fighting/angry; `kuli-ji` is angry/wild/fierce/vicious.", "Rule 105: kuli character terms."),
    ("orthography", "The corpus-normalized turtle form in new rows is `ngawiya`; Patz/source `ngawuya` remains logged as a spelling variant.", "Rule 105: ngawiya normalization."),
    ("orthography", "Cook/burn past is `wajun`; do not write `wajan`.", "Rule 105: wajul past guard."),
]

LEXEMES = [
    ("juburr", "particle", None, "NA", "be good at something", "batch-147: adjectival particle with dative complement."),
    ("binal-bajaku", "adjectival-particle", None, "NA", "know very much; know exactly", "batch-147: degree form from Patz §3.9.1."),
    ("binal-kari", "adjectival-particle", None, "NA", "not know", "batch-147: privative binal with dative topic."),
    ("binal-ma-l", "verb-itr", "l", "NA", "learn", "batch-147: inchoative from binal."),
    ("binal-bunga-l", "verb-tr", "l", "NA", "teach", "batch-147: causative from binal."),
    ("mala-", "prefix", None, "NA", "expert at; good at", "batch-147: productive with noun roots only."),
    ("mala-nganyi", "adjective", None, "NA", "competent; clever", "batch-147: skill/competence lexeme."),
    ("mala-minya", "noun", None, "neutral", "good hunter; game expert", "batch-147: mala- expert compound."),
    ("mala-kuyu", "noun", None, "neutral", "good fisherman", "batch-147: mala- expert compound."),
    ("mala-burri", "noun", None, "neutral", "good singer; song expert", "batch-147: mala- expert compound."),
    ("mala-mayi", "noun", None, "neutral", "good cook; food expert", "batch-147: mala- expert compound."),
    ("mala-balji", "noun", None, "neutral", "dillybag expert", "batch-147: mala- expert compound."),
    ("mala-bulki", "noun", None, "neutral", "cattle expert; stockman", "batch-147: mala- expert compound."),
    ("daki-daki", "adjective", None, "NA", "lazy; in the way", "batch-147: source usage Yundu daki-daki, dungayda."),
    ("majarr", "adjective", None, "NA", "lazy; no good for hunting or working", "batch-147: applies to dogs and people."),
    ("majamal-majamal", "adjective", None, "NA", "bossy", "batch-147: source phrase majamal-majamal bajaku."),
    ("nguju-wuri-y", "verb-itr", "y", "NA", "fool around; play about", "batch-147: surface nguju-wuri."),
    ("kuli-baka", "noun", None, "neutral", "person always fighting or angry", "batch-147: character lexeme."),
    ("mala-yirrkay", "verb-itr", "y", "NA", "admit; confess; tell the truth", "batch-147: source usage with jiba-badi-ny."),
    ("wawumal", "verb-itr", "l", "NA", "agree", "batch-147: dictionary usage Yundu wawumal, ngali dungay."),
    ("wawurr-wawurr", "adjective", None, "NA", "willing; glad", "batch-147: willingness/gladness state."),
    ("wawurr-wawurr-bunga-l", "verb-tr", "l", "NA", "make happy; make glad", "batch-147: causative gladness."),
    ("minday", "adjective", None, "NA", "tame; quiet; not afraid; confident", "batch-147: source pig-tame usage."),
    ("waymbul", "adverb", None, "NA", "slowly", "batch-147: source old-horse adverb row."),
    ("baja-burray", "adjective", None, "NA", "tired", "batch-147: tired from walking row."),
]


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-147-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 105 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to binal/juburr complement syntax, mala- expert compounds, stale lazy spellings, "
            "truth/lie/confession distinctions, final -iy surface discipline, shame causatives, minday scope, "
            "ngawiya spelling normalization, and wajun past."
        ),
        artifact_path="process_logs/batch-147-human-qualities-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 147: 50 accepted Rule 105 human-quality lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_147.py",
        artifact_path="batch_scripts/close_147.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-147-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())
