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

NOTES = (
    "LEXICAL: ANIMAL/BODY-FLESH EXPANSION AFTER RULE 132 (Rule 133). 50 rows. DESIGN: hand-authored rows "
    "foregrounding bajibay bone, bangkarr body/flesh, biji tail, jiba liver, and malbin upper leg, with minya "
    "meat/flesh-food and kuyu fish only as support nouns. SOURCE CONTROLS: exact dictionary snippets, Patz "
    "grammar examples, lexeme-table readback, and cross-corpus duplicate scan. REVIEW: dakil excluded because "
    "its live corpus sense is branch while the front-leg/hind-leg story needs a separate disambiguation pass; "
    "malbin held to upper leg only; jiba literal liver only; bangkarr body/flesh not steak; minya meat not generic "
    "animal. No instruments, comitatives, alienable possessive suffixes, temporal clitics, or new malbin case forms."
)

LESSONS = [
    ("process", "A lexical expansion after a construction batch should add only a small, source-checked semantic set, not a new construction family.", "Rule 133: lexical cadence."),
    ("process", "The batch recorded both selected senses and an explicitly excluded near-neighbor (`dakil`) before banking.", "Rule 133: exclusion logging."),
    ("process", "Underused heads such as `malbin` should first enter through plain state, perception, and reflexive frames before any new case forms are attempted.", "Rule 133: low-risk entry."),
    ("process", "Exact duplicate scanning stayed clean across all 50 planned Rule 133 surfaces before banking.", "Rule 133: duplicate guard."),
    ("lexicon", "`bajibay` was held to literal bone; metaphorical story-bone and cold-in-bones frames were not extended.", "Rule 133: bajibay."),
    ("lexicon", "`bangkarr` was held to body/flesh; the Patz text's steak-like use was noted but not generalized.", "Rule 133: bangkarr."),
    ("lexicon", "`biji` was held to animal tail in whole-part NPs such as `kuyu biji` and `kaya biji`.", "Rule 133: biji."),
    ("lexicon", "`jiba` was held to literal liver; grief/sadness compounds were excluded from the sentence rows.", "Rule 133: jiba."),
    ("lexicon", "`malbin` was admitted as upper leg only; no `dakil` contrast or hind-leg gloss was imported.", "Rule 133: malbin."),
    ("lexicon", "`minya` support rows used meat/flesh-food only, not the broader generic-animal classifier sense.", "Rule 133: minya support."),
    ("lexicon", "`kuyu` support rows used fish only, chiefly to host the sourced whole-part `kuyu biji` tail NP.", "Rule 133: kuyu support."),
    ("morphology", "Dative topics were limited to source-backed forms: `jiba-ka`, `bajibay-ngka`, `minya-ka`, `kuyu-ku`, and `bajibay-kari-ka`.", "Rule 133: dative bounds."),
    ("morphology", "No instrument or comitative morphology was admitted despite many tempting food/body object frames.", "Rule 133: no instruments/comitatives."),
    ("morphology", "No alienable possessive suffixes were used; English possessives remain renderings of inalienable whole-part apposition.", "Rule 133: possessive discipline."),
    ("morphology", "`malbin` was not inflected for dative, locative, instrumental, or comitative in this first lexical pass.", "Rule 133: malbin case restraint."),
    ("syntax", "Common-noun agents in perception, eating, cooking, placement, leaving, getting, giving, bite, and wash rows were ERG-marked.", "Rule 133: common-noun A."),
    ("syntax", "Pronoun A rows stayed bare in perception, placement, and wash rows.", "Rule 133: pronoun A."),
    ("syntax", "`babaji-y` ask-about rows kept the asker unmarked, with the person as LOC:pt and the topic as DAT.", "Rule 133: ask-about frame."),
    ("syntax", "Whole-part NPs remained bare appositions: `kuyu biji`, `kaya biji`, `karrkay bangkarr`, and person plus `malbin`.", "Rule 133: whole-part apposition."),
    ("fidelity", "No row used `dakil`, front-leg, or hind-leg wording; that contrast remains queued for a dedicated disambiguation pass.", "Rule 133: dakil queue."),
    ("fidelity", "Every English sentence maps directly to a practical household, food, or body-state scene; no symbolic/metaphorical senses were introduced.", "Rule 133: literal fidelity."),
    ("register", "The batch stays ordinary and inspectable: soreness, dry/good/tired states, seeing, eating, cooking, putting, leaving, taking, wanting, asking, giving, washing, biting, and lying.", "Rule 133: register scope."),
]

LEXEMES = [
    ("bajibay", "noun", None, "NA", "bone", "batch-175: literal bone only; used in state, perception, eat, put, take, want, ask, give, rest, and privative boneless-meat rows."),
    ("bangkarr", "noun", None, "NA", "body; flesh", "batch-175: body/flesh only; no steak drift and no instrument/comitative use."),
    ("biji", "noun", None, "NA", "tail", "batch-175: animal tail in whole-part apposition, especially kuyu biji and kaya biji."),
    ("jiba", "noun", None, "NA", "liver", "batch-175: literal liver only; jiba-badi grief compound excluded from row content."),
    ("malbin", "noun", None, "NA", "upper leg", "batch-175: upper leg only; entered through state, perception, and reflexive wash frames; no new case forms."),
    ("minya", "noun", None, "NA", "meat; flesh food", "batch-175: support head used as meat/flesh-food only, not generic animal."),
    ("kuyu", "noun", None, "NA", "fish", "batch-175: support head used as fish and as whole in kuyu biji tail rows."),
    ("jiba-ka", "case-form", None, "DAT", "for/about liver", "batch-175: directly modelled on Patz Text 76 line 81 Yundu jiba-ka wawu."),
    ("bajibay-ngka", "case-form", None, "DAT", "for/about a bone", "batch-175: y-final dative for bajibay in want/ask rows."),
    ("minya-ka", "case-form", None, "DAT", "for/about meat", "batch-175: retained meat dative support form."),
    ("kuyu-ku", "case-form", None, "DAT", "for/about fish", "batch-175: retained fish dative support form."),
    ("bajibay-kari", "adjective", None, "NA", "boneless; without bones", "batch-175: privative bone-less adjective."),
    ("bajibay-kari-ka", "case-form", None, "DAT", "for/about boneless", "batch-175: dative privative modifier in boneless-meat want row."),
    ("nyaji-l", "verb", "l", "NA", "see; perceive", "batch-175: perception rows with common-noun A ERG and pronoun A bare."),
    ("nuka-l", "verb", "l", "NA", "eat; consume", "batch-175: eating rows with bone, liver, and meat objects."),
    ("waju-l", "verb", "l", "NA", "cook; burn", "batch-175: liver cooking rows."),
    ("yijarri-l", "verb", "l", "NA", "put; place", "batch-175: bone, liver, and fish-tail placement rows."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-175: meat left in shade row."),
    ("mani-l", "verb", "l", "NA", "get; take", "batch-175: bone taken from ground row."),
    ("daya", "transitive-verb", None, "NA", "give", "batch-175: past dajin in liver/bone transfer rows; dictionary gives daya command/root 'give'."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-175: ask-about rows with unmarked S, person LOC:pt, and topic DAT."),
    ("julurri-l", "verb", "l", "NA", "wash", "batch-175: transitive body wash row."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-175: malbin reflexive wash rows."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-175: fish-tail and dog-tail affected-object rows."),
    ("wuna-y", "intransitive-verb", "y", "NA", "lie; be lying", "batch-175: bone, liver, and fish-tail rest-location rows."),
    ("kaka", "adjective", None, "NA", "sore; pain", "batch-175: upper-leg soreness only."),
    ("marral", "adjective", None, "NA", "dry", "batch-175: upper-leg, fish-tail, and bone state rows."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-175: body/bone/liver-meat state rows."),
    ("bajaburray", "adjective", None, "NA", "tired", "batch-175: body tired state row."),
    ("kalbay", "adjective", None, "NA", "long", "batch-175: dog-tail state row."),
    ("bubu-ngu", "case-form", None, "LOC", "on/in the ground", "batch-175: ground LOC in bone/liver rows."),
    ("bubu-muny", "case-form", None, "ABL", "from the ground", "batch-175: source in bone-getting row."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-175: bag LOC in bone/liver/fish-tail rows."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-175: shade LOC in meat/fish-tail rows."),
    ("babi-nda", "case-form", None, "LOC:pt", "at/to grandmother", "batch-175: recipient/addressee form."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "at/to father", "batch-175: ask-about addressee form."),
    ("ngamu-ndu", "case-form", None, "LOC:pt", "at/to mother", "batch-175: ask-about addressee form."),
    ("karrkay-anda", "case-form", None, "LOC:pt", "at/to child", "batch-175: transfer recipient form."),
    ("kaya", "noun", None, "NA", "dog", "batch-175: dog as whole for tail and as bone-eating/biting subject."),
    ("ngalngal", "noun", None, "NA", "crab", "batch-175: crab bite row."),
    ("bubu", "noun", None, "NA", "ground; country", "batch-175: ground support noun in locative/ablative rows."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-175: bag support noun in location rows."),
    ("wabarr", "noun", None, "NA", "shade", "batch-175: shade support noun in location 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}")

    total_rows = db.execute("SELECT COUNT(*) FROM sentences WHERE status!='rejected'").fetchone()[0]
    verified_before, words_before = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()

    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-175-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail=f"After banking, lint scanned {total_rows} rows and found 0 issues; verified total remained {verified_before} before close.",
        command="python3 lint_corpus.py",
        output_excerpt=f"lint: {total_rows} rows scanned, 0 issues flagged; GOAL METRIC: {verified_before} / 20000 verified sentences ({words_before or 0} 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 133 rows. Morphology checked ERG common-noun A, bare pronoun A, "
            "DAT topics, LOC/ABL support locations, LOC:pt recipients/addressees, privative -kari, reflexive -ji, and "
            "past/nonpast state frames. Lexicon checked target senses and excluded dakil, jiba-badi, bangkarr steak drift, "
            "and generic-animal minya. Syntax checked whole-part apposition, perception, food/object transitive rows, "
            "ask-about frames, transfer rows, reflexive wash, affected-object bite, and rest-location rows. Fidelity checked "
            "literal English-to-Kuku mapping and exact duplicate freedom. Register stayed practical."
        ),
        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: malbin=upper leg only with no new case forms; dakil excluded; "
            "biji=tail; bajibay=literal bone; jiba=literal liver; bangkarr=body/flesh; minya=meat/flesh-food only; "
            "no instruments, comitatives, alienable possessives, temporal clitics, or unsourced analogies."
        ),
        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 133 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_175.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 133 target heads, support heads, case forms, predicates, and support nouns.",
        artifact_path="batch_scripts/close_175.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 175: 50 accepted Rule 133 animal/body-flesh lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_175.py",
        artifact_path="batch_scripts/close_175.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-175-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__":
    raise SystemExit(main())
