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

NOTES = (
    "LEXICAL: BODY-PART EXPANSION (Rule 131). 50 rows. DESIGN: hand-authored rows drilling sourced body-part "
    "heads in inalienable state, perception, wash/reflexive wash, placement/location, affected-object, and a small "
    "compound set. SOURCE CONTROLS: exact dictionary entries, Patz grammar examples, lexeme-table readback, and "
    "cross-corpus duplicate scan. REVIEW: mara hand; jina foot only, not track/path; walu face; milka ear; miyil "
    "eye only, not tree; ngandal mouth; dukul head; muku back; bibar shin only, not ankle; kaka only sore/pain "
    "state, not a body-part noun. No new instruments, comitatives, alienable possessives, or temporal clitic frames."
)

LESSONS = [
    ("process", "A lexical expansion can still use only old syntactic frames; Rule 131 added body heads without opening new construction territory.", "Rule 131: lexical scope."),
    ("process", "Exact duplicate scan must run before banking; it caught the first planned `Karrkay milka-janan` row and forced a replacement.", "Rule 131: duplicate guard."),
    ("process", "The process log should record selected senses and excluded senses before close, not only after acceptance.", "Rule 131: process capture."),
    ("lexicon", "`mara` is the free noun root for hand; it was used as hand only.", "Rule 131: mara."),
    ("lexicon", "`jina` was held to foot only; track/path senses were excluded from all 50 rows.", "Rule 131: jina."),
    ("lexicon", "`walu` was held to face in both plain nouns and the `walu-wukurri-ny` compound.", "Rule 131: walu."),
    ("lexicon", "`milka` was held to ear in plain rows, `milka-kari`, and `milka-jana-ny`.", "Rule 131: milka."),
    ("lexicon", "`miyil` was held to eye; the poisonous-tree homonym was excluded.", "Rule 131: miyil."),
    ("lexicon", "`ngandal`, `dukul`, and `muku` were held to mouth, head, and back; extended/secondary senses were excluded.", "Rule 131: mouth/head/back."),
    ("lexicon", "`bibar` was admitted cautiously as shin because both dictionary and Patz case table support it; ankle sense stayed excluded.", "Rule 131: bibar."),
    ("lexicon", "`kaka` was not added as a target body-part head; it remains a sore/pain predicate.", "Rule 131: kaka."),
    ("morphology", "No instrument rows were admitted despite sourced body instruments elsewhere; Rule 131 stayed body-part lexical/appositional.", "Rule 131: no instruments."),
    ("morphology", "No comitatives, alienable possessive suffixes, or temporal clitic constructions were used.", "Rule 131: no extra morphology."),
    ("morphology", "Body locations were limited to source-backed or already logged forms: `mara-nga`, `jina-nga`, `muku-ngu`, `ngandal-ba`, and `bibar-a`.", "Rule 131: body locations."),
    ("syntax", "Common-noun `nyaji-l`, wash, placement, bite, lick, and drop agents were kept ergative; pronoun A stayed bare.", "Rule 131: transitive alignment."),
    ("syntax", "Reflexive wash and poke rows kept S bare rather than forcing ergative marking.", "Rule 131: reflexive rows."),
    ("syntax", "Whole-part apposition was used for body-part state and affected-object rows instead of alienable possessive suffixes.", "Rule 131: inalienable apposition."),
    ("fidelity", "English possessive translations are representational; the Kuku surfaces remain bare possessor plus body part where source supports inalienable body relations.", "Rule 131: possessive English."),
    ("fidelity", "Every row stayed exact-duplicate free after replacing the caught listening duplicate.", "Rule 131: duplicate outcome."),
    ("register", "The batch stays practical and bodily: washing, seeing, soreness, simple placement, biting/licking, stepping, deafness, sleeplessness, turning, and listening.", "Rule 131: register scope."),
]

LEXEMES = [
    ("mara", "noun", None, "NA", "hand", "batch-173: hand only; free noun root in Patz; no numeral or instrument import."),
    ("jina", "noun", None, "NA", "foot", "batch-173: foot only; track/path senses excluded."),
    ("walu", "noun", None, "NA", "face", "batch-173: face only; used in plain rows and walu-wukurri-ny."),
    ("milka", "noun", None, "NA", "ear", "batch-173: ear only; used in plain rows, milka-kari, and milka-jana-ny."),
    ("miyil", "noun", None, "NA", "eye", "batch-173: eye only; poisonous-tree homonym excluded."),
    ("ngandal", "noun", None, "NA", "mouth", "batch-173: mouth only; phonetic-table source checked."),
    ("dukul", "noun", None, "NA", "head", "batch-173: head only; boat/boss/tape-recorder extensions excluded."),
    ("muku", "noun", None, "NA", "back", "batch-173: back only; hawk sense excluded."),
    ("bibar", "noun", None, "NA", "shin", "batch-173: shin sense selected; ankle excluded."),
    ("kaka", "adjective", None, "NA", "sore; pain", "batch-173: sore/pain predicate only, not a body-part target."),
    ("mara-nga", "case-form", None, "LOC", "in/on the hand", "batch-173: body-part location form."),
    ("jina-nga", "case-form", None, "LOC", "on the foot", "batch-173: directly modelled on Patz foot-LOC."),
    ("muku-ngu", "case-form", None, "LOC", "on the back", "batch-173: retained body-part location form."),
    ("ngandal-ba", "case-form", None, "LOC", "in the mouth", "batch-173: retained mouth location form."),
    ("bibar-a", "case-form", None, "LOC", "on the shin", "batch-173: Patz case table gives bibar-a."),
    ("babi-nda", "case-form", None, "LOC:pt", "at/to grandmother", "batch-173: person location in body-location placement rows."),
    ("karrkay-anda", "case-form", None, "LOC:pt", "at/to child", "batch-173: person location in body-location placement rows."),
    ("ngawa-nda", "case-form", None, "LOC:pt", "at/to baby", "batch-173: person location in body-location placement rows."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "at/to father", "batch-173: person location in body-location placement rows."),
    ("jalbu-ndu", "case-form", None, "LOC:pt", "at/to woman", "batch-173: person location in stepping/placement rows."),
    ("mukul-dingkar-anda", "case-form", None, "LOC:pt", "at/to old man", "batch-173: person location in shin-placement row."),
    ("mukul-jalbu-ndu", "case-form", None, "LOC:pt", "at/to old woman", "batch-173: person location in back-drop row."),
    ("nyaji-l", "verb", "l", "NA", "see; perceive", "batch-173: perception rows with common-noun A ERG and pronoun A bare."),
    ("julurri-l", "verb", "l", "NA", "wash", "batch-173: transitive wash rows."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-173: reflexive wash rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-173: placement rows."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-173: body affected rows."),
    ("bija-l", "verb", "l", "NA", "lick", "batch-173: face/mouth affected rows."),
    ("baka-ji-y", "verb", "y", "NA", "poke oneself", "batch-173: foot poke-reflexive row."),
    ("narri-ji-y", "verb", "y", "NA", "happen to step on", "batch-173: foot stepping row."),
    ("dara-y-mani-l", "verb", "l", "NA", "drop; cause to fall", "batch-173: body-location drop rows."),
    ("milka-kari", "adjective", None, "NA", "deaf; no ears", "batch-173: privative body-part compound."),
    ("miyil-dandi", "adjective", None, "NA", "sleepless", "batch-173: sourced eye-hard compound."),
    ("walu-wukurri-y", "verb", "y", "NA", "turn around", "batch-173: sourced face-follow compound."),
    ("milka-jana-y", "verb", "y", "NA", "listen", "batch-173: sourced ear-stand compound."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-173: body-part state predicate."),
    ("duna", "adjective", None, "NA", "wet", "batch-173: body-part state predicate."),
    ("marral", "adjective", None, "NA", "dry", "batch-173: body-part state predicate."),
    ("yalbay", "adjective", None, "NA", "big", "batch-173: body-part state predicate."),
    ("bana", "noun", None, "NA", "water", "batch-173: placement object."),
    ("kulji", "noun", None, "NA", "stone; rock", "batch-173: stone only in body-location placement/drop rows."),
    ("juku", "noun", None, "NA", "stick; wood", "batch-173: stick object in drop row."),
    ("nganka", "noun", None, "NA", "flower", "batch-173: flower object in placement row."),
    ("ngalngal", "noun", None, "NA", "crab", "batch-173: crab biting row."),
    ("kaya", "noun", None, "NA", "dog", "batch-173: dog bite/lick 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-173-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,747 rows and found 0 issues; verified total remained 8,697 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8747 rows scanned, 0 issues flagged; GOAL METRIC: 8697 / 20000 verified sentences (94293 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 131 rows. Morphology checked ergative A, pronoun A, "
            "LOC:pt person forms, body LOC forms, reflexive -ji, privative -kari, compounds, past and state rows. "
            "Lexicon checked each body head and excluded senses. Syntax checked inalienable apposition, whole-part O, "
            "perception, wash, placement, affected-object, stepping, drop, and compound rows. Fidelity checked duplicate "
            "freedom and selected senses. Register stayed ordinary bodily/household narrative."
        ),
        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 instruments, no comitatives, no alienable possessive suffixes, "
            "no temporal clitics; jina=foot not track/path; miyil=eye not tree; bibar=shin not ankle; kaka=sore/pain "
            "predicate only; common-noun transitive agents ERG-marked; reflexive rows S-marked; exact duplicate replacement retained."
        ),
        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 131 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_173.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 131 body heads, case forms, predicates, and compounds.",
        artifact_path="batch_scripts/close_173.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 173: 50 accepted Rule 131 body-part lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_173.py",
        artifact_path="batch_scripts/close_173.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-173-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())
