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

NOTES = (
    "CONSTRUCTION: CONSOLIDATION AFTER RULE 131 (Rule 132). 50 rows. DESIGN: hand-authored consolidation of "
    "Rule 131 body-part heads in retained state, perception, transitive wash, reflexive wash, placement/location, "
    "affected-object, chance stepping, drop/cause-fall, privative, and compound frames. SOURCE CONTROLS: Rule 131 "
    "body-head decisions rechecked against Patz grammar examples and lexeme-table readback; exact duplicate scan "
    "clean. REVIEW: no new lexical field; jina foot not track/path; miyil eye not tree; bibar shin not ankle; "
    "kaka sore/pain only; no instruments, comitatives, alienable possessive suffixes, or temporal clitics; "
    "common-noun transitive A ERG, pronoun A bare, reflexive S bare."
)

LESSONS = [
    ("process", "A construction batch after a body-part lexical pass should change participant/frame pairings, not add another body lexeme.", "Rule 132: construction cadence."),
    ("process", "Exact duplicate scan stayed clean for all 50 planned Rule 132 rows before banking.", "Rule 132: duplicate scan."),
    ("process", "Source readback can reuse Rule 131 decisions only if the selected and excluded senses are restated in the new process log.", "Rule 132: source readback."),
    ("lexicon", "`mara` remained hand only in state, perception, wash, placement, bite, stepping, and drop frames.", "Rule 132: mara."),
    ("lexicon", "`jina` remained foot only; no track/path rows were admitted.", "Rule 132: jina."),
    ("lexicon", "`walu` remained face in state, perception, wash, and `walu-wukurri-ny` rows.", "Rule 132: walu."),
    ("lexicon", "`milka` remained ear in state, perception, and `milka-kari`; no instrument use was imported.", "Rule 132: milka."),
    ("lexicon", "`miyil` remained eye in state, perception, and `miyil-dandi`; tree sense excluded.", "Rule 132: miyil."),
    ("lexicon", "`ngandal`, `dukul`, and `muku` remained mouth, head, and back with secondary senses excluded.", "Rule 132: mouth/head/back."),
    ("lexicon", "`bibar` remained shin; ankle sense excluded again.", "Rule 132: bibar."),
    ("lexicon", "`kaka` remained sore/pain predicate only, not a concrete body-part noun.", "Rule 132: kaka."),
    ("morphology", "No body-part instrument forms were admitted: no `mara-bu`, `jina-bu`, `milka-bu`, `miyil-bu`, `ngandal-bu`, or analogues.", "Rule 132: no instruments."),
    ("morphology", "No comitatives, alienable possessive suffixes, or temporal clitic constructions were used.", "Rule 132: no extra morphology."),
    ("morphology", "Body-location forms stayed inside the logged set: `mara-nga`, `jina-nga`, `muku-ngu`, `ngandal-ba`, and `bibar-a`.", "Rule 132: body locations."),
    ("syntax", "Common-noun agents in perception, wash, placement, bite/lick, and drop rows were ERG-marked.", "Rule 132: common-noun A."),
    ("syntax", "Pronoun A rows stayed bare, including `Ngayu ... nyajin`, `Ngayu ... yijarrin`, and `Ngana ... yijarrin`.", "Rule 132: pronoun A."),
    ("syntax", "Reflexive wash rows kept S bare, not ERG-marked.", "Rule 132: reflexive S."),
    ("fidelity", "English possessives remain renderings of inalienable apposition; no Kuku alienable possessive suffix was used.", "Rule 132: possessive English."),
    ("fidelity", "`Kulji` remained stone in body-location placement/drop rows and did not drift to mountain.", "Rule 132: kulji."),
    ("register", "The batch stays bodily and practical: soreness, seeing, washing, putting water, biting/licking, stepping, dropping, deafness, sleeplessness, and turning.", "Rule 132: register scope."),
]

LEXEMES = [
    ("mara", "noun", None, "NA", "hand", "batch-174: hand only in construction consolidation; no instrument import."),
    ("jina", "noun", None, "NA", "foot", "batch-174: foot only; track/path excluded."),
    ("walu", "noun", None, "NA", "face", "batch-174: face only; includes walu-wukurri-ny."),
    ("milka", "noun", None, "NA", "ear", "batch-174: ear only; includes milka-kari, no milka-bu."),
    ("miyil", "noun", None, "NA", "eye", "batch-174: eye only; tree homonym excluded."),
    ("ngandal", "noun", None, "NA", "mouth", "batch-174: mouth only; no ngandal-bu."),
    ("dukul", "noun", None, "NA", "head", "batch-174: head only; extensions excluded."),
    ("muku", "noun", None, "NA", "back", "batch-174: back only; hawk sense excluded."),
    ("bibar", "noun", None, "NA", "shin", "batch-174: shin only; ankle excluded."),
    ("kaka", "adjective", None, "NA", "sore; pain", "batch-174: sore/pain predicate only."),
    ("mara-nga", "case-form", None, "LOC", "in/on the hand", "batch-174: retained body-part location."),
    ("jina-nga", "case-form", None, "LOC", "on the foot", "batch-174: retained Patz-backed foot LOC."),
    ("muku-ngu", "case-form", None, "LOC", "on the back", "batch-174: retained body-part location."),
    ("ngandal-ba", "case-form", None, "LOC", "in the mouth", "batch-174: retained body-part location."),
    ("bibar-a", "case-form", None, "LOC", "on the shin", "batch-174: retained Patz-backed shin LOC."),
    ("ngamu-ndu", "case-form", None, "LOC:pt", "at/to mother", "batch-174: person location in body-location rows."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "at/to father", "batch-174: person location in body-location rows."),
    ("babi-nda", "case-form", None, "LOC:pt", "at/to grandmother", "batch-174: person location in body-location rows."),
    ("kami-nda", "case-form", None, "LOC:pt", "at/to grandfather", "batch-174: person location in body-location rows."),
    ("maral-anda", "case-form", None, "LOC:pt", "at/to girl", "batch-174: person location in body-location rows."),
    ("karrkay-anda", "case-form", None, "LOC:pt", "at/to child", "batch-174: person location in body-location rows."),
    ("ngawa-nda", "case-form", None, "LOC:pt", "at/to baby", "batch-174: person location in body-location rows."),
    ("mukul-jalbu-ndu", "case-form", None, "LOC:pt", "at/to old woman", "batch-174: person location in body-location rows."),
    ("nyaji-l", "verb", "l", "NA", "see; perceive", "batch-174: matched common-noun/pronoun perception rows."),
    ("julurri-l", "verb", "l", "NA", "wash", "batch-174: transitive body-part wash rows."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-174: reflexive body-part wash rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-174: body-location placement rows."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-174: affected body-part rows."),
    ("bija-l", "verb", "l", "NA", "lick", "batch-174: affected head row."),
    ("narri-ji-y", "verb", "y", "NA", "happen to step on", "batch-174: chance stepping body-part rows."),
    ("dara-y-mani-l", "verb", "l", "NA", "drop; cause to fall", "batch-174: body-location drop rows."),
    ("milka-kari", "adjective", None, "NA", "deaf; no ears", "batch-174: privative compound retained."),
    ("miyil-dandi", "adjective", None, "NA", "sleepless", "batch-174: eye-hard compound retained."),
    ("walu-wukurri-y", "verb", "y", "NA", "turn around", "batch-174: face-follow compound retained."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-174: state predicate."),
    ("duna", "adjective", None, "NA", "wet", "batch-174: state predicate."),
    ("marral", "adjective", None, "NA", "dry", "batch-174: state predicate."),
    ("yalbay", "adjective", None, "NA", "big", "batch-174: retained via previous body-head rules; not foregrounded in rows."),
    ("bana", "noun", None, "NA", "water", "batch-174: placement object."),
    ("kulji", "noun", None, "NA", "stone; rock", "batch-174: stone only in placement/drop rows; not mountain."),
    ("juku", "noun", None, "NA", "stick; wood", "batch-174: stick object, never instrument."),
    ("nganka", "noun", None, "NA", "flower", "batch-174: flower object in placement row."),
    ("ngalngal", "noun", None, "NA", "crab", "batch-174: crab bite row."),
    ("kaya", "noun", None, "NA", "dog", "batch-174: dog bite/lick/turn 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-174-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,797 rows and found 0 issues; verified total remained 8,747 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8797 rows scanned, 0 issues flagged; GOAL METRIC: 8747 / 20000 verified sentences (94481 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 132 rows. Morphology checked ERG common-noun A, bare pronoun A, "
            "reflexive S, person LOC:pt, body LOC forms, privative, compounds, past, and state rows. Lexicon checked "
            "Rule 131 body-head sense boundaries. Syntax checked inalienable apposition, whole-part O, perception, wash, "
            "reflexive wash, placement, affected-object, chance stepping, drop, and compound rows. Fidelity checked "
            "duplicate freedom and no new instruments/comitatives/possessives. 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: construction-only after Rule 131; jina foot not track/path; miyil "
            "eye not tree; bibar shin not ankle; kaka sore/pain only; kulji stone not mountain; no body-part "
            "instrument rows; no alienable possessives; common-noun A ERG, pronoun A bare, reflexive S bare."
        ),
        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 132 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_174.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 132 body heads, case forms, predicates, and retained support heads.",
        artifact_path="batch_scripts/close_174.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 174: 50 accepted Rule 132 body-part construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_174.py",
        artifact_path="batch_scripts/close_174.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-174-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())
