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

NOTES = (
    "LEXICAL: ENVIRONMENTAL LEXICAL EXPANSION AFTER RULE 126 (Rule 127). 50 rows. DESIGN: hand-authored "
    "environmental and animal heads inside retained case frames, with no new morphology. SOURCE CONTROLS: exact "
    "dictionary and grammar readback for bana, baya, juku, buyku, jikan, wurun, ngurrban, muyar, jiri, wungar, "
    "buyi, jarba, bilngkumu, and yirku-yirku; baya possible-loan note recorded but not loan-logged because Patz says "
    "it is unsubstantiated. REVIEW: duplicate laugh-target row repaired before banking; common-noun perception A "
    "ERG, pronoun A bare, ask/laugh/comitative frames retained. PROCESS STORAGE: source readback, duplicate scan, "
    "static guards, lint, review, close, export, docs, and live checks are stored as process evidence."
)

LESSONS = [
    ("process", "A lexical batch can add many useful words without adding a single new morphosyntactic pattern.", "Rule 127: lexical-only expansion."),
    ("process", "Exact-surface duplicate scans remain necessary for laugh-target maintenance rows; Batch 169 repaired one before banking.", "Rule 127: duplicate repair."),
    ("process", "Source notes about uncertain etymology should be preserved without over-marking loans; `baya` is possible English-derived but not substantiated.", "Rule 127: etymology caution."),
    ("process", "Animal and weather heads should first enter through rest/perception/weather-safe rows before any dangerous semantic extension.", "Rule 127: conservative admission."),
    ("lexicon", "`bana` is water and is safe as object, LOC `bana-nga`, and sourced DAT topic `bana-ka`.", "Rule 127: bana."),
    ("lexicon", "`baya` is fire/firewood; in Batch 169 it is used as firewood object/rest subject, not as an unsourced verb.", "Rule 127: baya."),
    ("lexicon", "`juku` covers tree/wood/stick; use it carefully and do not derive new instruments beyond sourced `juku-ji`.", "Rule 127: juku."),
    ("lexicon", "`buyku`, `jikan`, and `wurun` are paperbark, grass, and humpy/shelter respectively.", "Rule 127: shelter/bush heads."),
    ("lexicon", "`ngurrban`, `muyar`, `jiri`, and `wungar` are cloud, wind, sky, and sun/day; use `nyaji-l` as see/hear when semantically appropriate.", "Rule 127: weather/sky heads."),
    ("lexicon", "`buyi`, `jarba`, `bilngkumu`, and `yirku-yirku` are bird, snake, crocodile, and frog; avoid turning animal nouns into instruments or agents without a source.", "Rule 127: animal heads."),
    ("morphology", "Retained LOC forms `bana-nga`, `juku-ngu`, and `jikan-ba` can be used where directly source-backed.", "Rule 127: source-backed locatives."),
    ("morphology", "`bayan-ka` and `bayan-muny` remain the transfer goal/source forms; pronoun A stays bare.", "Rule 127: transfer case."),
    ("morphology", "`bana-ka`, `kuku-ku`, `minya-ka`, and `mayngku-ku` are the admitted ask-about topics in this batch.", "Rule 127: DAT topics."),
    ("morphology", "The closed comitative set remains `ngawa-nji`, `jawun-unji`, `nganjan-anji`, `juku-ji`, and `kambi-ji`.", "Rule 127: closed comitatives."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked across humpy, cloud, wind, sky, bird, snake, and frog/crocodile rows.", "Rule 127: perception A marking."),
    ("syntax", "Pronoun A remains bare in matched perception/hearing and transfer rows.", "Rule 127: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about rows retain ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 127: ask-about syntax."),
    ("syntax", "`yajarri-l` laugh rows retain sourced DAT:pt targets; duplicate repairs should change only the target when the frame is otherwise good.", "Rule 127: laugh target syntax."),
    ("fidelity", "Do not over-translate `jikan-ba` or `bana-nga`: English may say into/in, but the gloss remains LOC.", "Rule 127: gloss honesty."),
    ("register", "The batch stays ordinary and practical: water, firewood, paperbark, grass, shelter, weather/sky, animals, seeing/hearing, asking, laughing, and moving with companions.", "Rule 127: register scope."),
]

LEXEMES = [
    ("bana", "noun", None, "NA", "water", "batch-169: water object, water LOC, and bana-ka ask-about topic."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-169: firewood rest/object; possible English etymology noted by Patz but unsubstantiated."),
    ("juku", "noun", None, "NA", "tree; wood; stick", "batch-169: stick/wood rest, object, tree LOC, and sourced juku-ji comitative."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-169: paperbark rest, leave, source, and goal object rows."),
    ("jikan", "noun", None, "NA", "grass", "batch-169: grass rest/object/LOC rows."),
    ("wurun", "noun", None, "NA", "humpy; shelter", "batch-169: humpy perceived object."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-169: cloud perceived object."),
    ("muyar", "noun", None, "NA", "wind", "batch-169: wind heard with nyaji-l."),
    ("jiri", "noun", None, "NA", "sky; heaven", "batch-169: sky perceived object."),
    ("wungar", "noun", None, "NA", "sun; day", "batch-169: sun perceived object."),
    ("buyi", "noun", None, "NA", "bird", "batch-169: bird perceived in tree."),
    ("jarba", "noun", None, "NA", "snake", "batch-169: snake rest/perception rows."),
    ("bilngkumu", "noun", None, "NA", "crocodile", "batch-169: crocodile rest/perception rows."),
    ("yirku-yirku", "noun", None, "NA", "frog", "batch-169: frog rest/perception rows."),
    ("bana-nga", "case-form", None, "LOC", "in the water", "batch-169: water LOC with frog and crocodile."),
    ("bana-ka", "case-form", None, "DAT", "about water", "batch-169: sourced water DAT topic."),
    ("juku-ngu", "case-form", None, "LOC", "in/on the tree", "batch-169: tree LOC with bird rows."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-169: closed sourced comitative."),
    ("jikan-ba", "case-form", None, "LOC", "in the grass", "batch-169: grass LOC with motion/staying."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-169: retained ground LOC."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-169: retained shade LOC."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-169: retained outside LOC."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-169: retained bag LOC."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-169: retained road LOC."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-169: retained camp LOC."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-169: retained transfer goal."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-169: retained transfer source."),
    ("babi-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandmother", "batch-169: ask/laugh person form."),
    ("kami-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandfather", "batch-169: ask/laugh person form."),
    ("ngamu-ndu", "case-form", None, "LOC:pt/DAT:pt", "at/to mother", "batch-169: ask/laugh person form."),
    ("nganjan-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to father", "batch-169: ask/laugh person form."),
    ("maral-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to the girl", "batch-169: ask person form."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-169: retained ask-about topic."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-169: retained ask-about topic."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-169: retained loan topic."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-169: closed comitative."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-169: closed comitative."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-169: closed comitative."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-169: closed comitative."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-169: rest rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-169: placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-169: paperbark leave row."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-169: transfer rows."),
    ("mani-l", "verb", "l", "NA", "get", "batch-169: water get row."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-169: perception/hearing rows."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-169: ask-about rows."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-169: laugh-target rows."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-169: closed-comitative motion rows."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-169: place-before-comitative staying row."),
]


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-169-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,547 rows and found 0 issues; verified total remained 8,497 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8547 rows scanned, 0 issues flagged; GOAL METRIC: 8497 / 20000 verified sentences (93569 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 127 rows. Morphology checked retained LOC, ABL, DAT, "
            "LOC:pt/DAT:pt, COMIT, ERG, past, and nonpast forms with no new analogy. Lexicon checked all "
            "environmental heads and the baya etymology caution. Syntax checked rest, placement, transfer, "
            "perception/hearing, ask-about, laugh targets, and closed comitatives. Fidelity checked duplicate repair, "
            "loan/contact flags, and gloss honesty for LOC forms. Register stayed ordinary and source-grounded."
        ),
        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 new morphology; baya possible-loan note recorded but not marked "
            "as a loan; mayngku and wulman loan/contact forms logged; common-noun nyaji-l perceivers ERG-marked; "
            "pronoun A bare; babaji-y askers not ERG-marked; yajarri-l targets DAT:pt; comitatives limited to the "
            "closed sourced set."
        ),
        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 127 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_169.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 127 heads, case forms, comitatives, and predicates.",
        artifact_path="batch_scripts/close_169.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 169: 50 accepted Rule 127 environmental lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_169.py",
        artifact_path="batch_scripts/close_169.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-169-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())
