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

NOTES = (
    "LEXICON: CAMP OBJECTS, CONTAINERS, AND EVERYDAY HOUSEHOLD/CRAFT IMPLEMENTS (Rule 107). 50 rows. DESIGN: "
    "concrete lexical batch after Rule 106 manner-adverb construction work. SOURCE CONTROLS: Patz camp setup and "
    "camp-preparation examples, balji/ngunyin/kurmun bag frames, jungkalu/bulin/dubal container frames, baya/waju-l "
    "fire frames, instrumentals with implements, and dictionary-verified material/object terms. PROCESS STORAGE: "
    "source pass, exclusions, duplicate preflight, lint outputs, five-lens review, close, export, and live-doc "
    "verification are stored in process_events and the batch process log."
)

LESSONS = [
    ("lexicon", "Bayan is camp/house/shelter. Use ngara-ny only for setting up camp/house, not as a generic make verb for bags or tools.", "Rule 107: bayan/ngara scope."),
    ("lexicon", "Baya covers fire/flame/firewood; waju-l covers cook/burn/light. Surface past remains wajun, not wajan.", "Rule 107: fire vocabulary guard."),
    ("syntax", "Implements stay instrumental with -bu: balur-bu, naybu-bu, jimal-bu, bangkal-bu, karra-bu. They are not agents.", "Rule 107: implement instrumental frame."),
    ("morphology", "Container locatives must follow stem class: balji-nga, jungkalu-ngu, bulin-ba, kurmun-ba, dubal-ba, marrakan-ba, jukar-a.", "Rule 107: container/object locatives."),
    ("lexicon", "Balji is the ordinary bag/dillybag term; ngunyin can be dillybag/bark-strip material but also has other senses, so context must select the craft sense.", "Rule 107: bag lexeme split."),
    ("lexicon", "Kurmun is a sack/bag and pairs safely with mumbal, balkal, and jarrakulba-nka carry-purpose frames.", "Rule 107: kurmun frames."),
    ("lexicon", "Yinkar is not an ordinary bag; because it is a dillybag for remains, it was source-checked but excluded from ordinary lexical training.", "Rule 107: yinkar exclusion."),
    ("lexicon", "Milbayarr was avoided because the dictionary has mixed place/euphemism/woomera material; balur is the safer ordinary spear-thrower entry.", "Rule 107: woomera entry choice."),
    ("lexicon", "Dubal is bark/coolamon/bark container in the rows here. Do not generalize it to every English bowl or ignore its funerary source senses.", "Rule 107: dubal caution."),
    ("lexicon", "Bangkal has homophones: the noun is cooking tongs; the verb is gather. Instrumental bangkal-bu selects the noun.", "Rule 107: bangkal homophone."),
    ("lexicon", "Ngunjil is charcoal/hot coals/hot ashes; it is not a synonym for baya fire.", "Rule 107: ngunjil guard."),
    ("lexicon", "Naybu is an attested knife loan and was used sparsely; do not let it open a modern household/tool loan list.", "Rule 107: loan restraint."),
    ("lexicon", "Bulin plate and jungkalu billycan are post-contact/container terms used only where source-backed.", "Rule 107: post-contact container restraint."),
    ("orthography", "Turtle remains ngawiya, not ngawuya; productive reduplication remains hyphenated; past -ny is analyzed, not leaked into surface forms.", "Rule 107: carried orthographic guards."),
]

LEXEMES = [
    ("bayan", "noun", None, "locative-ba", "camp; house; shelter", "batch-149: camp/house/shelter object/location rows."),
    ("ngara", "verb", "l/y-source", "NA", "set up camp/house", "batch-149: grammar-only camp setup with bayan ngara-ny."),
    ("baya", "noun", None, "locative-nga", "fire; flame; firewood", "batch-149: fire/firewood rows with mujal and waju-l."),
    ("ngunjil", "noun", None, "NA", "charcoal; hot coals; hot ashes", "batch-149: coals in fire; not fire itself."),
    ("jungkalu", "noun", None, "locative-ngu", "billycan", "batch-149: post-contact container; used sparsely."),
    ("bulin", "noun", None, "locative-ba", "plate", "batch-149: source-backed plate rows."),
    ("balji", "noun", None, "locative-nga", "bag; dillybag", "batch-149: ordinary bag/dillybag container rows."),
    ("ngunyin", "noun", None, "locative-nga", "dillybag; bark strips; web; placenta", "batch-149: used only in dillybag/craft sense."),
    ("kurmun", "noun", None, "locative-ba", "sack; bag", "batch-149: sack/bag rows including carry-purpose frame."),
    ("karra", "noun", None, "instrumental-bu", "rope; cord; string", "batch-149: rope as implement or object."),
    ("dubal", "noun", None, "locative-ba", "bark; coolamon; bark container", "batch-149: bark/coolamon container; not generic bowl."),
    ("yibuy", "noun", None, "ablative-muny", "loya cane; walking-stick material", "batch-149: material source for bag making/weaving."),
    ("birra", "noun", None, "NA", "leaf; lungs", "batch-149: leaf contents row."),
    ("kalka", "noun", None, "NA", "spear", "batch-149: spear quality and making rows."),
    ("balur", "noun", None, "instrumental-bu", "spear thrower; woomera", "batch-149: ordinary spear-thrower entry, chosen over Milbayarr."),
    ("naybu", "noun", None, "instrumental-bu", "knife", "batch-149: attested English loan, sparse knife rows."),
    ("jimal", "noun", None, "instrumental-bu", "fire stick", "batch-149: firestick as implement."),
    ("jaba", "noun", None, "NA", "stick; sapling; post; walking stick", "batch-149: simple stick object/location rows."),
    ("bangkal", "noun", None, "instrumental-bu", "tongs", "batch-149: noun sense tongs, distinct from gather verb."),
    ("kurrma", "noun", None, "locative-nga", "earth oven", "batch-149: cooking-earth-oven row with bangkal."),
    ("marrakan", "noun", None, "locative-ba", "red cedar; dugout canoe", "batch-149: dugout-canoe rows."),
    ("jalun", "noun", None, "locative-bu", "sea", "batch-149: canoe-at-sea row."),
    ("jukar", "noun", None, "locative-a", "sand", "batch-149: single-r locative jukar-a."),
    ("kambi", "noun", None, "NA", "clothing; flying fox", "batch-149: clothing sense selected by wash/lie predicates."),
    ("mumbal", "verb", "l", "NA", "put inside; insert", "batch-149: put into bag/sack/container rows."),
    ("nyangarril", "verb", "l", "NA", "pour; spill", "batch-149: pour into billycan/bark container rows."),
    ("julurril", "verb", "l", "NA", "wash", "batch-149: wash plate/billycan/clothing rows."),
    ("kajal", "verb", "l", "NA", "tie", "batch-149: tie sack with rope."),
    ("kuna-bungal", "verb", "l", "NA", "join; tie something to something else", "batch-149: tie rope to bag."),
    ("wukurril", "verb", "l", "NA", "follow; weave; make fence; imitate", "batch-149: weave bag/dillybag rows."),
    ("nyandal", "verb", "l", "NA", "chop", "batch-149: chop bark/coolamon material row."),
    ("karrbal", "verb", "l", "NA", "catch; grab; touch", "batch-149: grab food with tongs."),
    ("kulbal", "verb", "l", "NA", "pull; lift", "batch-149: pull canoe on sand."),
]


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-149-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 107 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to camp/setup scoping, object locative allomorphs, instrumental implement roles, "
            "loan restraint, bag/dillybag distinctions, dubal limits, bangkal homophone control, balur versus Milbayarr, "
            "ngawiya spelling, and exact duplicate avoidance."
        ),
        artifact_path="process_logs/batch-149-camp-objects-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 149: 50 accepted Rule 107 camp-object/container/implement rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_149.py",
        artifact_path="batch_scripts/close_149.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-149-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())
