#!/usr/bin/env python3
"""Close batch-177 after main-loop five-lens review."""

from __future__ import annotations

import datetime as dt
import json
import sqlite3

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

NOTES = (
    "LEXICAL EXPANSION: TORSO/LIMB BODY PARTS (Rule 135). 50 rows. TARGETS: damu chest, jibar stomach, "
    "jakay neck, binda shoulder, wakuy arm, wulu ankle, wurra navel. DESIGN: hand-authored source-backed "
    "lexical expansion using only proven body-part apposition, perception, transitive wash, reflexive wash, "
    "and affected-object bite frames. REVIEW: binda shoulder not fork; damu chest not hillside; jibar stomach "
    "not locational jibarr; wulu ankle not broadened to unsupported shin wording; wurra navel not umbilical-cord "
    "scene; no waba, jandal, dakil, target case forms, instruments, comitatives, possessive suffixes, temporal "
    "clitics, or unsourced analogies; common-noun A ERG, pronoun A bare, reflexive S unmarked."
)

LESSONS = [
    ("process", "A lexical body-part batch should keep constructional novelty at zero; Rule 135 used only old state, perception, wash, reflexive wash, and bite frames.", "Rule 135: lexical batch discipline."),
    ("process", "The batch excluded plausible but risky adjacent heads rather than forcing coverage: `waba`, `jandal`, `dakil`, and locational `jibarr` stayed out.", "Rule 135: exclusion discipline."),
    ("process", "Exact duplicate scanning stayed a pre-bank blocker over all accepted/revised and under-review non-rejected surfaces.", "Rule 135: duplicate guard."),
    ("lexicon", "`damu` was admitted only as chest; hillside sense was excluded by analysis and evidence.", "Rule 135: damu sense."),
    ("lexicon", "`jibar` was admitted only as stomach; locational `jibarr` was denied.", "Rule 135: jibar/jibarr contrast."),
    ("lexicon", "`jakay` was admitted as neck/back of neck, represented in English as neck.", "Rule 135: jakay sense."),
    ("lexicon", "`binda` was admitted only as shoulder; fork-in-tree/river senses were excluded.", "Rule 135: binda sense."),
    ("lexicon", "`wakuy` was admitted as arm, but `wakuy-mbu` stayed only a source note and no new case form was generated.", "Rule 135: wakuy restraint."),
    ("lexicon", "`wulu` was admitted as ankle; shin was not foregrounded in English rows.", "Rule 135: wulu sense."),
    ("lexicon", "`wurra` was admitted as navel; umbilical-cord scenes were not opened.", "Rule 135: wurra sense."),
    ("morphology", "Every target head remained bare; no dative, locative, ablative, instrumental, comitative, or compound target form was created.", "Rule 135: target case restraint."),
    ("morphology", "Common-noun transitive and perception agents were ERG-marked; pronoun agents stayed bare.", "Rule 135: A marking."),
    ("morphology", "Reflexive wash rows used unmarked S with `julurri-ji-ny`; no ERG appeared on reflexive subjects.", "Rule 135: reflexive wash."),
    ("morphology", "No instruments, comitatives, alienable possessive suffixes, temporal clitics, or degree morphology appeared.", "Rule 135: no extra morphology."),
    ("syntax", "Whole-plus-part apposition remained the core body-part NP shape across states, perception objects, wash objects, reflexive affected parts, and bite objects.", "Rule 135: inalienable apposition."),
    ("syntax", "Transitive wash and bite rows kept the affected person plus body part as one bare object phrase.", "Rule 135: affected object."),
    ("syntax", "Perception rows preserved the older common-noun/pronoun contrast without adding location, topic, or subordinate material.", "Rule 135: perception frame."),
    ("fidelity", "English possessive phrasing was mapped to inalienable apposition, not to Kuku possessive suffixes.", "Rule 135: possessive English."),
    ("fidelity", "The English labels were narrowed to the selected senses whenever the dictionary entry was polysemous.", "Rule 135: sense fidelity."),
    ("register", "Rows remained ordinary and short: body states, seeing, washing, washing oneself, and animal bites.", "Rule 135: register scope."),
    ("handoff", "Next cadence should consolidate Rule 135 constructions before opening another lexical field; keep the waba/jandal/dakil exclusions active.", "Rule 135: next cadence."),
]

LEXEMES = [
    ("damu", "noun", None, "NA", "chest", "batch-177: chest only; hillside sense excluded."),
    ("jibar", "noun", None, "NA", "stomach", "batch-177: stomach only; locational jibarr denied."),
    ("jakay", "noun", None, "NA", "neck; back of neck", "batch-177: neck/back-of-neck body-part sense."),
    ("binda", "noun", None, "NA", "shoulder", "batch-177: shoulder only; fork senses excluded."),
    ("wakuy", "noun", None, "NA", "arm", "batch-177: arm only; no new wakuy case form."),
    ("wulu", "noun", None, "NA", "ankle; shin", "batch-177: ankle selected; shin wording not foregrounded."),
    ("wurra", "noun", None, "NA", "navel; umbilical cord", "batch-177: navel selected; umbilical-cord scenes not opened."),
    ("nganjan", "noun", None, "NA", "father", "batch-177: kin possessor/perceiver/washed person in body-part rows."),
    ("ngamu", "noun", None, "NA", "mother", "batch-177: kin possessor/perceiver/washer in body-part rows."),
    ("babi", "noun", None, "NA", "grandmother", "batch-177: kin possessor/perceiver/washer in body-part rows."),
    ("kami", "noun", None, "NA", "grandfather", "batch-177: kin possessor/perceiver/affected person in body-part rows."),
    ("karrkay", "noun", None, "NA", "child", "batch-177: child whole in body-part apposition and A in perception row."),
    ("ngawa", "noun", None, "NA", "baby; infant", "batch-177: baby whole in neck, stomach, navel, and ankle rows."),
    ("dingkar", "noun", None, "NA", "man", "batch-177: person head in shoulder/neck perception rows and old-man compound."),
    ("jalbu", "noun", None, "NA", "woman", "batch-177: person head in shoulder, neck, ankle, and reflexive rows."),
    ("mukul", "adjective", None, "NA", "old", "batch-177: old-man compound in arm state/wash rows."),
    ("warru", "noun", None, "NA", "young man", "batch-177: young-man whole in neck and arm rows."),
    ("kaya", "noun", None, "NA", "dog", "batch-177: dog ERG A in affected bite rows."),
    ("ngalngal", "noun", None, "NA", "sand crab", "batch-177: crab ERG A in affected bite rows."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-177: bare pronoun A/S in perception and reflexive wash rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-177: bare pronoun A in perception row."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-177: bare pronoun A in perception row."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-177: perception rows with common-noun A ERG and pronoun A bare."),
    ("julurri-l", "verb", "l", "NA", "wash something", "batch-177: transitive wash rows with affected body-part objects."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-177: reflexive wash rows with selected body-part affected S."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-177: affected body-part bite rows."),
    ("kaka", "adjective", None, "NA", "sore; painful", "batch-177: bodily soreness predicate only."),
    ("marral", "adjective", None, "NA", "dry", "batch-177: dry state predicate with body parts."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-177: good state predicate with body parts."),
]


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-177-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 135 rows. Morphology checked zero target case forms, no "
            "instruments/comitatives/possessives/temporal clitics, common-noun A ERG, pronoun A bare, and unmarked "
            "reflexive S. Lexicon checked selected body-part senses for damu, jibar, jakay, binda, wakuy, wulu, and "
            "wurra, plus excluded waba, jandal, dakil, and locational jibarr. Syntax checked whole-plus-part apposition, "
            "perception, transitive wash, reflexive wash, and affected-object bite frames. Fidelity checked English "
            "possessives as apposition and narrowed polysemy. Register stayed ordinary."
        ),
        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 no waba, no jandal, no dakil, no target case forms, no instruments, no comitatives, "
            "no possessive suffixes, no temporal clitics, binda shoulder only, damu chest only, jibar stomach only, "
            "wulu ankle wording, and wurra navel wording."
        ),
        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 135 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_177.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 135 targets, participants, predicates, and pronouns.",
        artifact_path="batch_scripts/close_177.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 177: 50 accepted Rule 135 torso/limb body-part rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_177.py",
        artifact_path="batch_scripts/close_177.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-177-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())
