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

NOTES = (
    "CONSTRUCTION: CASE-FRAME CONSOLIDATION AFTER RULE 127 (Rule 128). 50 rows. DESIGN: hand-authored "
    "consolidation of environmental heads inside retained case frames, with no new lexical heads and no new "
    "morphology. SOURCE CONTROLS: exact dictionary/grammar/corpus readback for the Rule 127 heads, plus wurun-ba "
    "and janay for humpy rows; baya possible-loan note retained but not loan-logged. REVIEW: two duplicate "
    "ask/laugh rows repaired before banking; no new instruments/comitatives/possessives from juku or animal heads; "
    "common-noun perception A ERG, pronoun A bare, ask/laugh/comitative frames retained."
)

LESSONS = [
    ("process", "A construction batch after a lexical expansion should prove the new heads in old frames, not chase new vocabulary.", "Rule 128: construction cadence."),
    ("process", "Duplicate scans are especially important for ask/laugh maintenance rows; Batch 170 repaired two before banking.", "Rule 128: duplicate repair."),
    ("process", "Prior corpus rows can be source evidence for already admitted forms such as `wurun-ba` and `janay`, but the source trail must still be recorded.", "Rule 128: source trail."),
    ("lexicon", "`bana` remains water; `bana-nga` is LOC and `bana-ka` is a sourced DAT topic.", "Rule 128: bana."),
    ("lexicon", "`baya` remains fire/firewood; Patz's possible English etymology remains unsubstantiated and is not a loan flag.", "Rule 128: baya."),
    ("lexicon", "`juku` remains tree/wood/stick; `juku-ji` is allowed only as an already sourced comitative.", "Rule 128: juku."),
    ("lexicon", "`buyku`, `jikan`, and `wurun` remain paperbark, grass, and humpy/shelter.", "Rule 128: environmental nouns."),
    ("lexicon", "`ngurrban`, `muyar`, `jiri`, and `wungar` remain cloud, wind, sky, and sun/day.", "Rule 128: sky/weather nouns."),
    ("lexicon", "`buyi`, `jarba`, `bilngkumu`, and `yirku-yirku` remain bird, snake, crocodile, and frog, used only as rest or perceived objects here.", "Rule 128: animal nouns."),
    ("morphology", "No new instrument, comitative, or possessive morphology was derived from `juku` or animal heads.", "Rule 128: no new analogy."),
    ("morphology", "`bana-nga`, `juku-ngu`, `jikan-ba`, and `wurun-ba` are LOC forms; English may say in/into/to but the gloss stays LOC.", "Rule 128: LOC honesty."),
    ("morphology", "`bayan-ka` and `bayan-muny` remain the safe transfer goal/source forms.", "Rule 128: transfer case."),
    ("morphology", "The closed comitative set remains `ngawa-nji`, `jawun-unji`, `nganjan-anji`, `juku-ji`, and `kambi-ji`.", "Rule 128: closed comitatives."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked across humpy, cloud, wind, sky, bird, snake, crocodile, and frog rows.", "Rule 128: perception A marking."),
    ("syntax", "Pronoun A remains bare in matched perception/hearing and transfer rows.", "Rule 128: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about rows retain ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 128: ask-about syntax."),
    ("syntax", "`yajarri-l` laugh rows retain sourced DAT:pt targets; repairs changed only the target, not the frame.", "Rule 128: laugh target syntax."),
    ("fidelity", "Animal heads are not promoted to agents or causes in this consolidation pass; they remain rest/perceived objects.", "Rule 128: animal fidelity."),
    ("fidelity", "`wurun bayan-ba janay` is safer than forcing humpy into a lie/rest frame; use sourced predicates that match the noun.", "Rule 128: humpy predicate choice."),
    ("register", "The batch remains plain and practical: water, firewood, wood, paperbark, grass, humpy, weather/sky, animals, seeing/hearing, asking, laughing, and companion motion.", "Rule 128: register scope."),
]

LEXEMES = [
    ("bana", "noun", None, "NA", "water", "batch-170: water rest, transfer object, LOC, and DAT-topic rows."),
    ("baya", "noun", None, "NA", "fire; firewood", "batch-170: firewood rest/object/transfer rows; possible loan note not loan-logged."),
    ("juku", "noun", None, "NA", "tree; wood; stick", "batch-170: stick/wood rest/object/tree-LOC/comitative rows."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-170: paperbark rest/object/source rows."),
    ("jikan", "noun", None, "NA", "grass", "batch-170: grass rest/object/LOC rows."),
    ("wurun", "noun", None, "NA", "humpy; shelter", "batch-170: humpy stand/perception/LOC rows."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-170: cloud perception rows."),
    ("muyar", "noun", None, "NA", "wind", "batch-170: wind hearing rows."),
    ("jiri", "noun", None, "NA", "sky; heaven", "batch-170: sky perception row."),
    ("wungar", "noun", None, "NA", "sun; day", "batch-170: sun perception row."),
    ("buyi", "noun", None, "NA", "bird", "batch-170: bird rest/perception rows."),
    ("jarba", "noun", None, "NA", "snake", "batch-170: snake rest/perception rows only."),
    ("bilngkumu", "noun", None, "NA", "crocodile", "batch-170: crocodile rest/perception rows only."),
    ("yirku-yirku", "noun", None, "NA", "frog", "batch-170: frog rest/perception rows only."),
    ("bana-nga", "case-form", None, "LOC", "in the water", "batch-170: water LOC in comitative motion rows."),
    ("bana-ka", "case-form", None, "DAT", "about water", "batch-170: water DAT topic."),
    ("juku-ngu", "case-form", None, "LOC", "in/on the tree", "batch-170: tree LOC in bird and comitative rows."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-170: closed sourced comitative."),
    ("jikan-ba", "case-form", None, "LOC", "in/on the grass", "batch-170: grass LOC in comitative rows."),
    ("wurun-ba", "case-form", None, "LOC", "in the humpy", "batch-170: humpy LOC with bunday and ngawa-nji."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-170: retained ground LOC."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-170: retained shade LOC."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-170: retained outside LOC."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-170: retained bag LOC."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-170: retained road LOC."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-170: retained camp LOC."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-170: retained transfer goal."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-170: retained transfer source."),
    ("babi-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandmother", "batch-170: ask/laugh person form."),
    ("kami-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandfather", "batch-170: ask/laugh person form."),
    ("ngamu-ndu", "case-form", None, "LOC:pt/DAT:pt", "at/to mother", "batch-170: laugh person form."),
    ("nganjan-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to father", "batch-170: duplicate-repair target and ask form."),
    ("maral-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to the girl", "batch-170: laugh person form."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-170: retained ask-about topic."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-170: retained ask-about topic."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-170: retained loan topic."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-170: closed comitative."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-170: closed comitative."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-170: closed comitative."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-170: closed comitative."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-170: rest rows."),
    ("jana-y", "verb", "y", "NA", "stand; be", "batch-170: humpy stand row."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-170: bird sitting and humpy staying rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-170: placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-170: firewood/grass/paperbark leave rows."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-170: transfer rows."),
    ("mani-l", "verb", "l", "NA", "get", "batch-170: firewood get row."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-170: perception/hearing rows."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-170: ask-about rows."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-170: laugh-target rows."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-170: closed-comitative motion 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-170-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,597 rows and found 0 issues; verified total remained 8,547 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8597 rows scanned, 0 issues flagged; GOAL METRIC: 8547 / 20000 verified sentences (93748 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 128 rows. Morphology checked retained LOC, ABL, DAT, "
            "LOC:pt/DAT:pt, COMIT, ERG, past, and nonpast forms with no new instrument/comitative/possessive analogy. "
            "Lexicon checked all Rule 127 heads, wurun-ba, janay, and the baya etymology caution. Syntax checked rest, "
            "standing, placement, transfer, perception/hearing, ask-about, laugh targets, and closed comitatives. "
            "Fidelity checked duplicate repairs, animal-head restrictions, and LOC gloss honesty. Register stayed plain."
        ),
        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 lexical heads; no new morphology; no instruments from juku or "
            "animal heads; baya not loan-logged; 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 128 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_170.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 128 heads, case forms, comitatives, and predicates.",
        artifact_path="batch_scripts/close_170.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 170: 50 accepted Rule 128 construction rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_170.py",
        artifact_path="batch_scripts/close_170.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-170-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())
