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

NOTES = (
    "CONSTRUCTION: LEXICAL-HEAD CASE-FRAME CONSOLIDATION (Rule 124). 50 rows. DESIGN: hand-authored consolidation "
    "of Rule 123 lexical heads across retained Rule 122/123 case frames: place/source/rest, object location/source/goal, "
    "perception A-marking contrasts, ask-about DAT topics, laugh DAT:pt targets, closed comitatives, and two fixed "
    "possessive object NPs. SOURCE CONTROLS: exact dictionary/grammar readback for ngunyin, yinkar, makarr, karra, "
    "kaku, dumbul, bikibiki, mayngku, kuku, wungar, wulman, place/source forms, DAT topics, comitatives, and retained "
    "predicates. REVIEW: planned duplicate surfaces were repaired before banking; five-lens review passed all 50 rows. "
    "PROCESS STORAGE: source readback, duplicate scan, static guards, lint, review, close, export, docs, and live checks "
    "are stored as process evidence."
)

LESSONS = [
    ("process", "Exact-surface duplicate scanning must happen before banking; Batch 166 replaced a planned duplicate laugh row before insertion.", "Rule 124: duplicate scan before bank."),
    ("process", "Fresh consolidation can be achieved by changing a controlled location or target while preserving the same source-backed case frame.", "Rule 124: fresh surface strategy."),
    ("lexicon", "`ngunyin` remains the dilly-bag sense; do not import the attested `ngunyin-ji` into the open comitative pattern.", "Rule 124: ngunyin boundary."),
    ("lexicon", "`yinkar` must stay narrow as a remains dilly bag in English and gloss.", "Rule 124: yinkar specificity."),
    ("lexicon", "`kaku` is the lawyer-cane-top noun in this batch, never the unrelated wait expression.", "Rule 124: kaku sense split."),
    ("lexicon", "`kuku` may function as news/talk/language, but each English row should expose the intended sense.", "Rule 124: kuku sense discipline."),
    ("lexicon", "`wulman` is accepted as old man/old person from grammar narrative sources, but this batch still avoids new wulman case forms.", "Rule 124: wulman caution."),
    ("lexicon", "`bikibiki` and `mayngku` remain attested loans and are recorded in `loans_used` where they occur.", "Rule 124: loan transparency."),
    ("morphology", "`baral-ba`, `bubu-ngu`, `wabarr-ba`, `ngalkal-ba`, `jikan-ba`, `balji-nga`, `bayan-ba`, `bayan-ka`, `bayan-muny`, `jalun-bu`, `jalun-muny`, and `wawubaja-nga` remain fixed source-backed forms.", "Rule 124: case-form inventory."),
    ("morphology", "`kuku-ku`, `mayngku-ku`, and `mayi-ka` are DAT topics in ask-about rows; the person asked remains LOC:pt.", "Rule 124: ask-about morphology."),
    ("morphology", "`yajarri-l` targets require sourced DAT:pt suffixes such as `-nda`, `-ndu`, `-anka`, and `-anda`.", "Rule 124: laugh target morphology."),
    ("morphology", "The comitative inventory remains closed to `ngawa-nji`, `nganjan-anji`, `jawun-unji`, `juku-ji`, and `kambi-ji`.", "Rule 124: closed comitatives."),
    ("morphology", "`mayi kaya-nga` and `kambi ngamu-ngu` are reused only as fixed possessive object NPs with explicit POSS glossing.", "Rule 124: possessive boundary."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked even when the object is a recently added lexical head.", "Rule 124: perception common-noun A."),
    ("syntax", "Pronoun A remains bare in matched `nyaji-l`, `wundi-l`, and transfer rows.", "Rule 124: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about rows keep the asker as ABS/S, not as an ergative transitive A.", "Rule 124: ask-about syntax."),
    ("syntax", "Object rows keep the moved or perceived lexical object overt before place/source/goal phrases.", "Rule 124: object visibility."),
    ("fidelity", "Rows with `jalun-bu` or `wawubaja-nga` as goal/location should be glossed as LOC while English may render the motion endpoint.", "Rule 124: LOC goal fidelity."),
    ("fidelity", "The duplicate-repair row `Babi maral-anda yajarrin` preserves target morphology and changes only the target participant.", "Rule 124: repair fidelity."),
    ("register", "The batch stays in ordinary country/camp material culture and participant interaction, pending elder verification.", "Rule 124: register scope."),
]

LEXEMES = [
    ("ngunyin", "noun", None, "NA", "dilly bag", "batch-166: retained dilly-bag sense only; no ngunyin-ji import."),
    ("yinkar", "noun", None, "NA", "dilly bag for holding remains", "batch-166: translated as remains dilly bag in all rows."),
    ("makarr", "noun", None, "NA", "fish net", "batch-166: consolidated across rest, put, take, and see frames."),
    ("karra", "noun", None, "NA", "rope; cord; string", "batch-166: consolidated across rest, leave, take, and see frames."),
    ("kaku", "noun", None, "NA", "lawyer-cane top", "batch-166: noun sense only."),
    ("dumbul", "noun", None, "NA", "bark; hard outer covering", "batch-166: bark sense in rest, source, and perception frames."),
    ("bikibiki", "noun", None, "NA", "pig", "batch-166: attested loan in source/rest consolidation."),
    ("mayngku", "noun", None, "NA", "mango", "batch-166: attested loan in rest, get, and ask-about rows."),
    ("kuku", "noun", None, "NA", "news; language; talk", "batch-166: news sense in source, transfer, and ask-about rows."),
    ("wungar", "noun", None, "NA", "sun", "batch-166: sun as perception object."),
    ("wulman", "noun", None, "NA", "old man; old person; husband", "batch-166: participant noun from grammar narrative sources; no new case forms coined."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-166: retained ground LOC in rest, placement, perception, and possessive rows."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-166: retained road LOC/goal; baral-muny blocked."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-166: retained shade LOC in rest, leave, perception, and comitative rows."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-166: retained outside LOC in rest, leave, perception, and comitative rows."),
    ("jikan-ba", "case-form", None, "LOC", "in/on the grass", "batch-166: retained grass LOC in bark perception row."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-166: retained bag LOC with bark rest row."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-166: retained camp/house LOC with mani-l row."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-166: retained DAT goal with rope transfer row."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-166: retained source with pig, bark, stick, and possessive rows."),
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-166: retained sea LOC/goal in rest, comitative, and transfer rows."),
    ("jalun-muny", "case-form", None, "ABL", "from the sea", "batch-166: retained source with news, old man, and transfer rows."),
    ("wawubaja-nga", "case-form", None, "LOC", "at/to the river", "batch-166: retained river LOC/goal in fish-net transfer row."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-166: source-backed DAT topic in ask-about rows."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-166: source-backed DAT topic in ask-about rows."),
    ("mayi-ka", "case-form", None, "DAT", "about food", "batch-166: retained DAT topic in ask-about row."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-166: closed-comitative member retained only."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-166: closed-comitative member retained only."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-166: closed-comitative member retained only."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-166: closed-comitative member retained only."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-166: closed-comitative member retained only."),
    ("mayi kaya-nga", "possessive-np", None, "POSS.ABS", "the dog's food", "batch-166: fixed Patz-backed possessive object reused only."),
    ("kambi ngamu-ngu", "possessive-np", None, "POSS.ABS", "mother's clothes", "batch-166: fixed Patz-backed possessive object reused only."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-166: rest rows with checked lexical heads."),
    ("kada-y", "verb", "y", "NA", "come", "batch-166: source/comitative source rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-166: placement rows with overt lexical objects."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-166: leave rows with yinkar, karra, and fixed possessive object."),
    ("mani-l", "verb", "l", "NA", "get", "batch-166: mango object at camp."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-166: transfer rows with bark, news, net, rope, and possessive object."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-166: perception rows with common-noun/pronoun A contrast."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-166: ask-about frame with DAT topics."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-166: laugh-target rows with DAT:pt targets."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-166: nonpast staying row with ngawa-nji comitative."),
]


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-166-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After banking, lint scanned 8,397 rows and found 0 issues; verified total remained 8,347 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8397 rows scanned, 0 issues flagged; GOAL METRIC: 8347 / 20000 verified sentences (93011 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 124 rows. Morphology checked retained LOC, ABL, DAT, DAT:pt, "
            "LOC:pt, COMIT, POSS, ERG, past, and nonpast forms. Lexicon checked every content word against dictionary "
            "or Patz evidence and retained sense restrictions. Syntax checked object visibility, common-noun ERG "
            "perception A, bare pronoun A, ask-about, laugh targets, transfer source/goal, and closed comitative frames. "
            "Fidelity checked yinkar specificity, kaku noun sense, LOC-as-goal English renderings, and duplicate repairs. "
            "Register stayed ordinary camp/country material and participant interaction."
        ),
        artifact_path=PROCESS_LOG,
        created_at=NOW,
    )
    record_event(
        db,
        batch_label=LABEL,
        phase="review",
        event_type="review-detail",
        actor="claude-main",
        detail=(
            "Final review retained these decisions: no ngunyin-ji; no new comitatives; no new possessive templates; "
            "no baral-muny; no ergative babaji-y askers; common-noun nyaji-l perceivers ERG-marked; pronoun A bare; "
            "yajarri-l targets DAT:pt; yinkar translated as remains dilly bag; kaku translated as lawyer-cane top."
        ),
        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 124 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_166.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 124 heads, case forms, DAT topics, comitatives, possessives, and predicates.",
        artifact_path="batch_scripts/close_166.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 166: 50 accepted Rule 124 consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_166.py",
        artifact_path="batch_scripts/close_166.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-166-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())
