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

NOTES = (
    "CONSTRUCTION: PLACE/SOURCE/OBJECT/PARTICIPANT CASE-FRAME CONSOLIDATION (Rule 122). 50 rows. DESIGN: "
    "hand-authored consolidation of Rule 121 source-backed heads inside place versus source, object plus location, "
    "transfer source/goal, perception A-marking, ask-about, laugh-target, limited comitative, and Patz-backed "
    "possessive object frames. SOURCE CONTROLS: dictionary.yaml exact readback for every base head and verb head; "
    "Patz grammar checks for jalun-bu/jalun-muny, bayan-muny/bayan-ka, wawubaja-nga, madja-muny, baral-ba, "
    "ngalkal-ba, wabarr-ba, bubu-ngu, jikan-ba, balji-nga, wujurr-bu, ngawa-nji, nganjan-anji, jawun-unji, "
    "juku-ji, kambi-ji, mayi kaya-nga, kambi ngamu-ngu, babaji-y, yajarri-l, and nyaji-l. PROCESS STORAGE: "
    "source readback, static guards, duplicate scan, lint, five-lens review, close, export, docs, and live checks "
    "are stored as process evidence."
)

LESSONS = [
    ("morphology", "`jalun-bu` and `jalun-muny` remain the sea place/source contrast; they must not be collapsed in English or analysis.", "Rule 122: sea LOC/ABL contrast."),
    ("morphology", "`baral-ba` is safe for road place/goal here; `baral-muny` remains unlicensed for this corpus until directly sourced.", "Rule 122: road case boundary."),
    ("morphology", "`bubu-ngu`, `jikan-ba`, `wabarr-ba`, and `ngalkal-ba` are retained as memorized source-backed locatives, not rederived by a new allomorph rule.", "Rule 122: locative allomorph discipline."),
    ("morphology", "`bayan-muny` is source; `bayan-ka` is DAT goal/topic. The batch keeps these functions distinct.", "Rule 122: house/camp source versus DAT."),
    ("morphology", "`balji-nga` is a sourced bag-LOC form; it is not generalized here into an unrestricted container paradigm.", "Rule 122: bag locative limit."),
    ("morphology", "`ngawa-nji`, `nganjan-anji`, `jawun-unji`, `juku-ji`, and `kambi-ji` are the entire comitative set allowed in this batch.", "Rule 122: closed comitative set."),
    ("morphology", "`mayi kaya-nga` and `kambi ngamu-ngu` remain the only productive-looking possessive NPs admitted; no new possessor templates were coined.", "Rule 122: possessive ceiling."),
    ("syntax", "Common-noun `nyaji-l` perceivers take ERG in these transitive perception rows.", "Rule 122: perception A marking."),
    ("syntax", "Pronoun A with `nyaji-l`, `wundi-l`, and other transitive predicates remains unmarked in the corpus style.", "Rule 122: pronoun A contrast."),
    ("syntax", "`nyaji-l` covers see and hear; sound-source rows can use `ngangkurr`/`wulngku` plus ABL or LOC without inventing a separate hearing verb.", "Rule 122: perception predicate range."),
    ("syntax", "`babaji-y` ask-about rows keep ABS/S asker, LOC:pt person asked, and DAT topic; no asker receives ERG.", "Rule 122: ask-about frame."),
    ("syntax", "`yajarri-l` laugh rows keep the laugher as intransitive S and the target in DAT:pt.", "Rule 122: laugh-target frame."),
    ("syntax", "Object-location rows keep the object overt before the place phrase, avoiding a bare place-only paraphrase.", "Rule 122: object visibility."),
    ("syntax", "Transfer rows distinguish ABL source from DAT goal while keeping the moved object overt.", "Rule 122: transfer argument visibility."),
    ("lexicon", "`dawar` remains the safe star lexeme, while `kija` is glossed only as moon/month.", "Rule 122: celestial split."),
    ("lexicon", "`kambi` is used in the clothing sense in object/comitative/possessive rows; the flying-fox sense is not intended there.", "Rule 122: kambi sense control."),
    ("lexicon", "`baya` is translated as firewood only where the English makes that intended dictionary sense explicit.", "Rule 122: baya sense control."),
    ("fidelity", "`bundanday` is nonpast reduplicated posture/stay and receives present English in rows 41-42.", "Rule 122: nonpast fidelity."),
    ("register", "The batch stays in plain camp/country register: people, kin, food, water, ordinary objects, animals, places, and everyday actions.", "Rule 122: register scope."),
    ("process", "The batch proves the guard layer should check both morphology and construction-specific traps, especially `babaji-y` ERG drift and laugh-target suffix coverage.", "Rule 122: guard lesson."),
]

LEXEMES = [
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-164: sea LOC used in place, getting, and comitative-go rows."),
    ("jalun-muny", "case-form", None, "ABL", "from the sea", "batch-164: sea ABL used in source and heard-song rows."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-164: road LOC used in posture, motion, placement, and comitative rows."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-164: outside LOC used in posture, perception, and possessed-food rows."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-164: shade LOC used with sitting, placing, cooking, and staying."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-164: ground LOC used with sitting and putting food."),
    ("jikan-ba", "case-form", None, "LOC", "in/on the grass", "batch-164: grass LOC used with snake, meat, and perception rows."),
    ("madja-muny", "case-form", None, "ABL", "from the scrub/rainforest", "batch-164: scrub ABL used with coming and firewood source."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-164: house source used with baby, clothes, song, and comitative rows."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-164: DAT goal/topic in ask-about and transfer rows."),
    ("wawubaja-nga", "case-form", None, "LOC", "at/in the river", "batch-164: river LOC used in mussel and crocodile perception rows."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-164: bag LOC used with the dog's food."),
    ("mayi-ka", "case-form", None, "DAT", "about food", "batch-164: ask-about DAT topic."),
    ("bana-ka", "case-form", None, "DAT", "about water", "batch-164: ask-about DAT topic."),
    ("kalka-ka", "case-form", None, "DAT", "about the spear", "batch-164: ask-about DAT topic."),
    ("balji-ka", "case-form", None, "DAT", "about the bag/dillybag", "batch-164: ask-about DAT topic."),
    ("babi-nda", "case-form", None, "LOC:pt", "to/at grandmother", "batch-164: person asked in ask-about frame."),
    ("kami-nda", "case-form", None, "DAT:pt", "to/at grandfather", "batch-164: ask-about person and laugh target."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "to/at father", "batch-164: person asked in ask-about frame."),
    ("ngamu-ndu", "case-form", None, "LOC:pt", "to/at mother", "batch-164: person asked in ask-about frame."),
    ("maral-anda", "case-form", None, "LOC:pt", "to/at the girl", "batch-164: person asked in ask-about frame."),
    ("karrkay-anka", "case-form", None, "DAT:pt", "at the child", "batch-164: laugh target."),
    ("nganjan-anka", "case-form", None, "DAT:pt", "at father", "batch-164: laugh target."),
    ("warru-ndu", "case-form", None, "DAT:pt", "at the young man", "batch-164: laugh target."),
    ("jalbu-ndu", "case-form", None, "DAT:pt", "at the woman", "batch-164: laugh target."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-164: sourced baby comitative used with staying rows."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-164: sourced father comitative used with sea motion."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-164: sourced friend comitative used with road motion."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-164: sourced stick comitative used with scrub source."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-164: sourced clothes comitative used with house source."),
    ("mayi kaya-nga", "possessive-np", None, "POSS.ABS", "the dog's food", "batch-164: Patz-backed possessive object in leave/put rows."),
    ("kambi ngamu-ngu", "possessive-np", None, "POSS.ABS", "mother's clothes", "batch-164: Patz-backed possessive object in transfer rows."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-164: ask-about frame with ABS/S asker, LOC:pt person, DAT topic."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-164: laugh-target rows with DAT:pt target."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-164: perception rows contrasting ERG common-noun A and unmarked pronoun A."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-164: transfer rows with source/goal and overt object."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-164: object-location placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-164: leave rows with overt object and location."),
    ("dawar", "noun", None, "NA", "star", "batch-164: safe star lexeme in night perception row."),
    ("kija", "noun", None, "NA", "moon; month", "batch-164: moon-only use in night perception row."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-164: firewood sense in scrub-source row."),
    ("kambi", "noun", None, "NA", "clothes; flying fox", "batch-164: clothing sense in object, comitative, and possessive rows."),
]


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-164-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After banking Batch 164 under review, lint scanned 8,297 rows and found 0 issues; verified total remained 8,247 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8297 rows scanned, 0 issues flagged; GOAL METRIC: 8247 / 20000 verified sentences (92633 Kuku words)",
        artifact_path=PROCESS_LOG,
        created_at=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 122 rows with no sentence-content repairs. Morphology checked "
            "LOC/ABL/DAT/DAT:pt/LOC:pt/COMIT/POSS forms and tense morphology. Lexicon checked every content head "
            "against dictionary/Patz evidence. Syntax checked object visibility, common-noun ERG perception A, "
            "unmarked pronoun A, ask-about, laugh target, transfer source/goal, and closed comitative frames. "
            "Fidelity checked English tense/source/goal wording. Register stayed plain camp/country speech."
        ),
        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 164 review. Explicit retained decisions: no baral-muny; no "
            "new comitatives; no new possessive templates; no ergative babaji-y askers; yajarri-l targets carry "
            "DAT:pt; kija moon-only; dawar star; common-noun nyaji-l perceivers ERG-marked while pronouns remain bare."
        ),
        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 122 lessons covering morphology, syntax, lexicon, fidelity, register, and process safeguards.",
        artifact_path="batch_scripts/close_164.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 122 case forms, construction predicates, possessives, comitatives, and guarded lexical heads.",
        artifact_path="batch_scripts/close_164.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 164: 50 accepted Rule 122 case-frame consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_164.py",
        artifact_path="batch_scripts/close_164.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-164-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())
