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

NOTES = (
    "LEXICAL: SOURCE-BACKED LEXICAL EXPANSION INSIDE RULE 122 FRAMES (Rule 123). 50 rows. DESIGN: "
    "hand-authored ordinary-head expansion while preserving the Rule 122 place/source, object-location, transfer, "
    "perception, ask-about, laugh-target, closed-comitative, and fixed possessive frames. SOURCE CONTROLS: exact "
    "dictionary/grammar readback for ngunyin, yinkar, makarr, karra, kaku, dumbul, bikibiki, mayngku, kuku, "
    "wungar, wulman, kuku-ku, mayngku-ku, and retained Rule 122 forms. REVIEW: one under-review fidelity repair "
    "changed vague 'special dilly bag' to source-faithful 'remains dilly bag' for yinkar before final pass. "
    "PROCESS STORAGE: source readback, static guards, duplicate scan, lint, five-lens review, close, export, docs, "
    "and live checks are stored as process evidence."
)

LESSONS = [
    ("lexicon", "`ngunyin` is polysemous, but Batch 165 uses only the dilly-bag sense.", "Rule 123: ngunyin sense discipline."),
    ("lexicon", "`yinkar` is narrower than a generic bag: a dilly bag for holding remains. English/gloss must expose that sense.", "Rule 123: yinkar fidelity."),
    ("lexicon", "`makarr` is a fish net and can appear as a moved/seen object inside existing object frames.", "Rule 123: makarr source."),
    ("lexicon", "`karra` is rope/cord/string; keep it as an ordinary object unless a separate construction source is checked.", "Rule 123: karra source."),
    ("lexicon", "`kaku` in this batch is the noun 'lawyer-cane top', not the grammar's unrelated wait expression.", "Rule 123: kaku sense split."),
    ("lexicon", "`dumbul` is bark or hard outer covering; Batch 165 uses the bark sense explicitly.", "Rule 123: dumbul sense."),
    ("lexicon", "`bikibiki` and `mayngku` are attested loans. They are allowed, but `loans_used` records them.", "Rule 123: attested loan handling."),
    ("lexicon", "`kuku` covers news/language/talk. Batch 165 keeps English as news or language/news-DAT where that is intended.", "Rule 123: kuku sense."),
    ("lexicon", "`wungar` is sun; do not confuse it with `wujurr-bu` night/darkness time location.", "Rule 123: wungar/wujurr split."),
    ("lexicon", "`wulman` is admitted from grammar narrative examples as old man/old person, but it is not used to coin new case forms.", "Rule 123: wulman caution."),
    ("morphology", "`kuku-ku` and `mayngku-ku` are grammar-sourced DAT topics, so they are safe in `babaji-y` ask-about rows.", "Rule 123: sourced DAT topics."),
    ("morphology", "`ngunyin-ji` is attested but deliberately not imported; the comitative set remains closed in this batch.", "Rule 123: no new comitative import."),
    ("morphology", "`baral-ba` remains the road place/goal form; `baral-muny` remains blocked.", "Rule 123: road case boundary."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked even when the lexical object changes.", "Rule 123: perception A marking."),
    ("syntax", "Pronoun A remains unmarked in matching perception and transfer rows.", "Rule 123: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about still requires ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 123: ask-about continuity."),
    ("syntax", "`yajarri-l` laugh targets still require DAT:pt target case; changing the subject does not change the target frame.", "Rule 123: laugh target continuity."),
    ("syntax", "Object rows keep new lexical objects overt before the location/source/goal phrase.", "Rule 123: object visibility."),
    ("fidelity", "The row-12 yinkar repair shows why source glosses must be specific, not merely plausible.", "Rule 123: fidelity repair lesson."),
    ("register", "The new vocabulary remains ordinary camp/country material: bags, net, rope, bark, mango, pig, news, sun, and kin/participant talk.", "Rule 123: register scope."),
]

LEXEMES = [
    ("ngunyin", "noun", None, "NA", "dilly bag; bark/web/placenta by polysemy", "batch-165: used only in the dilly-bag sense."),
    ("yinkar", "noun", None, "NA", "dilly bag for holding remains", "batch-165: English/gloss repaired to remains dilly bag before close."),
    ("makarr", "noun", None, "NA", "fish net", "batch-165: used as object in put/get/see rows; Patz ex.162 supports makarr with wundi-l."),
    ("karra", "noun", None, "NA", "rope; cord; string", "batch-165: used as overt object in placement row."),
    ("kaku", "noun", None, "NA", "lawyer-cane top", "batch-165: noun sense only, not the wait expression."),
    ("dumbul", "noun", None, "NA", "bark; hard outer covering", "batch-165: bark sense in rest/source row."),
    ("bikibiki", "noun", None, "NA", "pig", "batch-165: attested loan used in rest/perception rows."),
    ("mayngku", "noun", None, "NA", "mango", "batch-165: attested loan used in rest/transfer/perception/ask rows."),
    ("kuku", "noun", None, "NA", "news; language; talk", "batch-165: news/language sense used in source, transfer, hear, and ask rows."),
    ("wungar", "noun", None, "NA", "sun", "batch-165: sun used as perception object outside."),
    ("wulman", "noun", None, "NA", "old man; old person; husband", "batch-165: grammar-backed participant noun, no new case forms coined."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-165: Patz ex.584-sourced DAT topic in ask-about rows."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-165: Patz ex.602-sourced DAT topic in ask-about rows."),
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-165: retained sea LOC with new objects/participants."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-165: retained source with news, old man, mango, and possessive rows."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-165: retained DAT goal with mango and possessive rows."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-165: retained road place/goal; no baral-muny."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-165: retained outside LOC with new objects."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-165: retained shade LOC with new objects."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-165: retained ground LOC with new objects."),
    ("jikan-ba", "case-form", None, "LOC", "in/on the grass", "batch-165: retained grass LOC with pig/bark rows."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-165: retained bag LOC with mango, kaku, and possessive rows."),
    ("madja-muny", "case-form", None, "ABL", "from the scrub/rainforest", "batch-165: retained scrub source with bark."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-165: closed-comitative set retained."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-165: closed-comitative set retained."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-165: closed-comitative set retained."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-165: closed-comitative set retained."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-165: closed-comitative set retained."),
    ("mayi kaya-nga", "possessive-np", None, "POSS.ABS", "the dog's food", "batch-165: fixed Patz-backed possessive object reused only."),
    ("kambi ngamu-ngu", "possessive-np", None, "POSS.ABS", "mother's clothes", "batch-165: fixed Patz-backed possessive object reused only."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-165: ask-about frame with kuku-ku and mayngku-ku topics."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-165: laugh-target rows with DAT:pt targets."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-165: perception rows with new lexical objects."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-165: transfer rows with mango/news/possessive objects."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-165: placement rows with new lexical objects."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-165: leave rows with yinkar and possessed food."),
]


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-165-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After the row-12 fidelity repair and rebank, lint scanned 8,347 rows and found 0 issues; verified total remained 8,297 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8347 rows scanned, 0 issues flagged; GOAL METRIC: 8297 / 20000 verified sentences (92822 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 123 rows after the under-review yinkar fidelity repair. "
            "Morphology checked retained case forms, closed comitatives, POSS NPs, ERG/DAT/LOC/ABL, and past/nonpast. "
            "Lexicon checked every foregrounded head against dictionary/Patz evidence and sense notes. Syntax checked "
            "object visibility, common-noun ERG perception A, unmarked pronoun A, ask-about, laugh targets, transfer "
            "source/goal, and closed comitative frames. Fidelity checked yinkar specificity, loan senses, news/language "
            "uses of kuku, and wungar/wujurr separation. 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=(
            "Final review retained these decisions: no ngunyin-ji despite attestation; no new comitatives; no new "
            "possessive templates; no baral-muny; no ergative babaji-y askers; yajarri-l targets carry DAT:pt; "
            "common-noun nyaji-l perceivers ERG-marked; pronoun A remains bare; yinkar translated as remains dilly bag."
        ),
        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 123 lessons covering lexical senses, morphology, syntax, fidelity, register, and process safeguards.",
        artifact_path="batch_scripts/close_165.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 123 lexical heads, source-backed DAT topics, retained case forms, predicates, comitatives, and possessives.",
        artifact_path="batch_scripts/close_165.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 165: 50 accepted Rule 123 lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_165.py",
        artifact_path="batch_scripts/close_165.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-165-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())
