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

NOTES = (
    "LEXICAL: SOURCE-BACKED PLACE, OBJECT, AND PARTICIPANT LEXICON (Rule 121). 50 rows. DESIGN: "
    "hand-authored lexical variation inside established Rule 118-120 case frames: places, ordinary objects, "
    "participants, animals, sound/weather/celestial heads, sourced comitatives, and Patz-backed possessive objects. "
    "SOURCE CONTROLS: dictionary.yaml entries for every content head; Patz grammar for jalun-bu/jalun-muny, "
    "baral-ba, ngalkal-ba, wabarr-ba, jikan-ba, bubu-ngu, wawubaja-nga/wawubaja-muny, bayan-ba/bayan-muny, "
    "manjal-muny, madja-muny, ngawa-nji, mayi kaya-nga, kambi ngamu-ngu, ask-about, laugh target, transfer, and "
    "nyaji-l A marking. PROCESS STORAGE: source pass, static-guard repair, duplicate scan, lint, no-repair five-lens "
    "review, close, export, docs, and live verification are stored."
)

LESSONS = [
    ("morphology", "`jalun-bu` and `jalun-muny` are the safe sea LOC/ABL forms for this batch.", "Rule 121: sea place/source."),
    ("morphology", "`baral-ba`, `ngalkal-ba`, `wabarr-ba`, `jikan-ba`, and `bubu-ngu` are kept as sourced locative forms; no new allomorphs were coined.", "Rule 121: place LOC allomorphs."),
    ("morphology", "`wawubaja-muny`, `bayan-muny`, `manjal-muny`, and `madja-muny` use established ABL/source behavior.", "Rule 121: source forms."),
    ("morphology", "`ngawa-nji` is admitted only because Patz ex.549 directly sources it; it is not a free invitation to derive new comitatives.", "Rule 121: ngawa-nji source."),
    ("morphology", "The comitative set for this batch remains closed: `ngawa-nji`, `nganjan-anji`, `jawun-unji`, `juku-ji`, and `kambi-ji`.", "Rule 121: comitative closure."),
    ("morphology", "`mayi kaya-nga` and `kambi ngamu-ngu` remain the only possessive object NPs added in this batch.", "Rule 121: possessive limit."),
    ("morphology", "`kija` is retained only in the moon sense and `dawar` remains the star lexeme.", "Rule 121: celestial guard."),
    ("syntax", "Common-noun perceivers with `nyaji-l` are ERG-marked; pronoun A rows remain unmarked.", "Rule 121: perception A marking."),
    ("syntax", "`babaji-y` ask-about rows keep ABS/S asker, LOC:pt person asked, and a sourced DAT topic.", "Rule 121: ask-about frame."),
    ("syntax", "`yajarri-l` laugh rows keep DAT:pt targets, while the laugher remains intransitive S.", "Rule 121: laugh target frame."),
    ("syntax", "Transfer rows retain visible moved objects plus LOC:pt recipient, DAT goal, or ABL source.", "Rule 121: transfer frame."),
    ("syntax", "Object-location rows keep the object overt before adding place information.", "Rule 121: object visibility."),
    ("lexicon", "`baya` is used in its source-backed fire/firewood sense; the English exposes firewood where that sense is intended.", "Rule 121: baya sense."),
    ("lexicon", "`kambi` is used in the clothing sense in clothing/possessive rows; no flying-fox sense is implied there.", "Rule 121: kambi sense."),
    ("lexicon", "`jarramali` is used only in thunderstorm/thunder sense, with English making the intended sense explicit.", "Rule 121: jarramali sense."),
    ("lexicon", "`ngangkurr` is a barking sound noun, not an invented general noise term.", "Rule 121: sound noun discipline."),
    ("fidelity", "Nonpast forms such as `wunanay`, `bundanday`, and `kaday` are translated with present/future English cues rather than past English.", "Rule 121: tense fidelity."),
    ("fidelity", "Comitative rows are translated plainly as accompaniment, not as carrying, having, or instrument unless separately sourced.", "Rule 121: comitative fidelity."),
    ("register", "The batch voice stays plain camp/country speech: people, food, objects, weather, animals, and everyday movement.", "Rule 121: register scope."),
    ("process", "Static guards are only useful when they are themselves tested: Batch 163 recorded and repaired an over-escaped regex guard before successful banking.", "Rule 121: guard repair evidence."),
]

LEXEMES = [
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-163: sea LOC used in stay/call/get/go rows."),
    ("jalun-muny", "case-form", None, "ABL", "from the sea", "batch-163: sea ABL used with come/hear/wind rows."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-163: road LOC used in posture, motion, and object-placement rows."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-163: outside LOC used in posture, leaving, seeing, and rain rows."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-163: shade LOC used in sleep/place/leave rows."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-163: ground LOC used in posture row."),
    ("jikan-ba", "case-form", None, "LOC", "in/on the grass", "batch-163: grass LOC used with snake, wallaby, meat, and perception rows."),
    ("madja-muny", "case-form", None, "ABL", "from the scrub/rainforest", "batch-163: scrub ABL used with firewood and comitative source rows."),
    ("wawubaja-nga", "case-form", None, "LOC", "at/in the river", "batch-163: river LOC used with mussel/crocodile rows."),
    ("wawubaja-muny", "case-form", None, "ABL", "from the river", "batch-163: river source used with stone-taking row."),
    ("bayan-ka", "case-form", None, "DAT", "to camp/house", "batch-163: camp goal used with wundi-l and possessed food."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-163: house source used with barking/bag rows."),
    ("manjal-muny", "case-form", None, "ABL", "from the mountain", "batch-163: mountain source used with jarramali."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-163: Patz ex.549-sourced comitative."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-163: retained sourced potent comitative."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-163: retained sourced potent comitative."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-163: retained sourced neutral comitative."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-163: retained sourced neutral comitative."),
    ("mayi kaya-nga", "possessive-np", None, "POSS.ABS", "the dog's food", "batch-163: Patz-backed possessive object reused in handling/perception rows."),
    ("kambi ngamu-ngu", "possessive-np", None, "POSS.ABS", "mother's clothes", "batch-163: Patz-backed possessive object reused in leave/put rows."),
    ("jalun", "noun", None, "NA", "sea", "batch-163: place noun checked in dictionary and Patz."),
    ("baral", "noun", None, "NA", "road; path", "batch-163: road/path noun checked and case-marked."),
    ("ngalkal", "noun", None, "NA", "outside", "batch-163: outside place noun checked."),
    ("wabarr", "noun", None, "NA", "shade", "batch-163: shade noun checked."),
    ("bubu", "noun", None, "NA", "ground; country", "batch-163: ground noun checked."),
    ("jikan", "noun", None, "NA", "grass", "batch-163: grass noun checked."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-163: firewood sense used explicitly."),
    ("jungkalu", "noun", None, "NA", "billycan", "batch-163: ordinary object in placement row."),
    ("kalka", "noun", None, "NA", "spear", "batch-163: ordinary object and ask-topic row."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-163: ordinary container/location noun."),
    ("kambi", "noun", None, "NA", "clothes; flying fox", "batch-163: clothing sense used in object/possessive rows."),
    ("kuyu", "noun", None, "NA", "fish", "batch-163: sea-getting object."),
    ("mukirr", "noun", None, "NA", "mussel", "batch-163: river-getting object."),
    ("minya", "noun", None, "NA", "meat; animal", "batch-163: meat object in eating row."),
    ("kulji", "noun", None, "NA", "stone; pebble", "batch-163: moved object from river."),
    ("bilngkumu", "noun", None, "NA", "crocodile", "batch-163: river perception object."),
    ("ngangkurr", "noun", None, "NA", "barking sound", "batch-163: heard sound noun, not general noise."),
    ("wulngku", "noun", None, "NA", "song", "batch-163: heard sound/song noun."),
    ("jarramali", "noun", None, "NA", "thunder; thunderstorm", "batch-163: thunderstorm sense with mountain source."),
    ("dawar", "noun", None, "NA", "star", "batch-163: safe star lexeme."),
    ("kija", "noun", None, "NA", "moon; month", "batch-163: moon-only guard retained."),
]


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-163-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 121 rows with no sentence-content repairs. Morphology checked "
            "LOC/ABL allomorphs, Patz-sourced ngawa-nji, closed comitative inventory, possessive object forms, past "
            "surfaces, and nonpast surfaces. Lexicon checked every content head against dictionary/Patz evidence. "
            "Syntax checked ERG common-noun nyaji-l perceivers, pronoun A, ask-about, DAT:pt laugh targets, transfer "
            "arguments, and overt objects. Fidelity kept English close to Kuku tense and source frames. Register stayed "
            "plain camp/country lexical drill pending elder verification."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="review-detail",
        actor="claude-main",
        detail=(
            "No row repairs were required during Batch 163 review. Explicit retained decisions: `jalun-bu`/`jalun-muny` "
            "are sea LOC/ABL; `ngawa-nji` is admitted only from Patz ex.549; no new possessive templates; no yunga-l; "
            "no maja-nga; `kija` moon-only; `dawar` star; common-noun perception A marked ERG."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="lesson-inventory",
        actor="claude-main",
        detail=f"Inserted {len(LESSONS)} Rule 121 lessons covering morphology, syntax, lexicon, fidelity, register, and process safeguards.",
        artifact_path="batch_scripts/close_163.py",
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="lexeme-source-log",
        actor="claude-main",
        detail=f"Inserted {len(LEXEMES)} lexeme/source-log rows for Rule 121 place, object, participant, comitative, possessive, and sound/weather/celestial forms.",
        artifact_path="batch_scripts/close_163.py",
        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 163: 50 accepted Rule 121 lexical-support rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_163.py",
        artifact_path="batch_scripts/close_163.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]
    under_review_remaining = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").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-163-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, under_review={under_review_remaining}, "
        f"verified corpus={verified}"
    )
    return 0


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