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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 135 (Rule 136). 50 rows. TARGETS RETAINED: damu chest, jibar stomach, "
    "jakay neck, binda shoulder, wakuy arm, wulu ankle, wurra navel. DESIGN: no new lexical field; reused Rule 135 "
    "heads in appositional state, perception, transitive wash, reflexive wash, and affected-object bite frames. "
    "REVIEW: no waba, jandal, dakil, locational jibarr, target case forms, instruments, comitatives, possessive "
    "suffixes, temporal clitics, or unsourced analogies; binda shoulder not fork, damu chest not hillside, jibar "
    "stomach not jibarr, wulu ankle wording, wurra navel wording; common-noun A ERG, pronoun A bare, reflexive S "
    "unmarked."
)

LESSONS = [
    ("process", "A construction consolidation after Rule 135 should recombine the same heads in proven frames rather than admitting another lexical field.", "Rule 136: construction cadence."),
    ("process", "Rule 136 repeated the Rule 135 source readback and exclusions, because construction reuse can drift into adjacent senses.", "Rule 136: repeated source controls."),
    ("process", "Exact duplicate scanning remained a pre-bank blocker; the batch used new surfaces rather than overwriting or duplicating older rows.", "Rule 136: duplicate guard."),
    ("lexicon", "`damu` stayed chest only; hillside sense did not enter any English, Kuku, or analysis field.", "Rule 136: damu."),
    ("lexicon", "`jibar` stayed stomach only; locational `jibarr` was explicitly denied.", "Rule 136: jibar/jibarr."),
    ("lexicon", "`jakay` stayed neck/back-of-neck, represented as neck.", "Rule 136: jakay."),
    ("lexicon", "`binda` stayed shoulder only; fork senses were excluded again.", "Rule 136: binda."),
    ("lexicon", "`wakuy` stayed arm; no `wakuy-mbu` or other case form appeared.", "Rule 136: wakuy."),
    ("lexicon", "`wulu` stayed ankle wording; shin was not opened as a scene.", "Rule 136: wulu."),
    ("lexicon", "`wurra` stayed navel wording; umbilical-cord scenes were not opened.", "Rule 136: wurra."),
    ("lexicon", "`bajaybajay`, `junkurr`, `yalbay`, `bajaku`, `kaka`, `marral`, and `ngulkurr` were used only as already source-checked state predicates/modifiers.", "Rule 136: state predicates."),
    ("morphology", "All target heads stayed bare; no dative, locative, ablative, instrumental, comitative, or compound target form appeared.", "Rule 136: target case restraint."),
    ("morphology", "Common-noun A in perception, wash, and bite rows was ERG-marked; pronoun A rows stayed bare.", "Rule 136: A marking."),
    ("morphology", "Reflexive wash rows used unmarked S plus `julurri-ji-ny`; no ERG appeared on reflexive subjects.", "Rule 136: reflexive wash."),
    ("morphology", "No instruments, comitatives, alienable possessive suffixes, temporal clitics, or carry-over Rule 133/134 support heads appeared.", "Rule 136: no extra morphology."),
    ("syntax", "Whole-plus-part apposition remained the body-part NP shape across states, perception objects, wash objects, reflexive affected parts, and bite objects.", "Rule 136: inalienable apposition."),
    ("syntax", "State rows consolidated optional body-part modifiers and predicates without adding case or possession.", "Rule 136: state syntax."),
    ("syntax", "Transitive wash and bite rows kept the affected person plus body part as one bare object phrase.", "Rule 136: affected-object syntax."),
    ("fidelity", "English possessive phrasing was interpreted as inalienable apposition, not Kuku possessive morphology.", "Rule 136: possessive English."),
    ("fidelity", "Rows with polysemous heads were narrowed in English: chest, stomach, shoulder, ankle, and navel only.", "Rule 136: sense fidelity."),
    ("register", "The batch stays ordinary and practical: sore/dry/good/painful/strong/big body states, seeing, washing, washing oneself, and bites.", "Rule 136: register scope."),
    ("handoff", "Next cadence may return to lexical expansion only after a fresh source pass; keep Rule 135/136 exclusions active.", "Rule 136: next cadence."),
]

LEXEMES = [
    ("damu", "noun", None, "NA", "chest", "batch-178: construction consolidation retained chest only."),
    ("jibar", "noun", None, "NA", "stomach", "batch-178: stomach only; locational jibarr denied again."),
    ("jakay", "noun", None, "NA", "neck; back of neck", "batch-178: neck/back-of-neck body-part sense."),
    ("binda", "noun", None, "NA", "shoulder", "batch-178: shoulder only; fork senses excluded again."),
    ("wakuy", "noun", None, "NA", "arm", "batch-178: arm only; no wakuy case form."),
    ("wulu", "noun", None, "NA", "ankle; shin", "batch-178: ankle wording retained; shin scene not opened."),
    ("wurra", "noun", None, "NA", "navel; umbilical cord", "batch-178: navel wording retained; umbilical-cord scene not opened."),
    ("bajaybajay", "adjective", None, "NA", "painful", "batch-178: painful body-state predicate."),
    ("junkurr", "noun", None, "NA", "strength; strong", "batch-178: strength/strong body-state predicate with shoulder/arm."),
    ("yalbay", "adjective", None, "NA", "big", "batch-178: body-part modifier/predicate in appositional state row."),
    ("bajaku", "degree", None, "NA", "very", "batch-178: degree particle in very-sore chest row."),
    ("kaka", "adjective", None, "NA", "sore; painful", "batch-178: bodily soreness predicate only."),
    ("marral", "adjective", None, "NA", "dry", "batch-178: dry state predicate with body parts."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-178: good state predicate with body parts."),
    ("nganjan", "noun", None, "NA", "father", "batch-178: kin possessor/perceiver/washed or bitten person."),
    ("ngamu", "noun", None, "NA", "mother", "batch-178: kin possessor/perceiver/washer or affected person."),
    ("babi", "noun", None, "NA", "grandmother", "batch-178: kin possessor/perceiver/washed or reflexive subject."),
    ("kami", "noun", None, "NA", "grandfather", "batch-178: kin possessor/perceiver/washer or affected person."),
    ("karrkay", "noun", None, "NA", "child", "batch-178: child whole, A, and reflexive S in body-part rows."),
    ("ngawa", "noun", None, "NA", "baby; infant", "batch-178: baby whole in stomach/navel/ankle/arm rows."),
    ("dingkar", "noun", None, "NA", "man", "batch-178: man whole/perceiver and old-man compound support."),
    ("jalbu", "noun", None, "NA", "woman", "batch-178: woman whole/perceiver/washer/affected person."),
    ("mukul", "adjective", None, "NA", "old", "batch-178: old-man compound support."),
    ("warru", "noun", None, "NA", "young man", "batch-178: young-man whole/affected person/reflexive S."),
    ("kaya", "noun", None, "NA", "dog", "batch-178: dog ERG A in bite rows."),
    ("ngalngal", "noun", None, "NA", "sand crab", "batch-178: crab ERG A in bite rows."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-178: bare pronoun A/S in perception and reflexive wash rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-178: bare pronoun A in perception row."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-178: bare pronoun A in perception row."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-178: perception rows with common-noun A ERG and pronoun A bare."),
    ("julurri-l", "verb", "l", "NA", "wash something", "batch-178: transitive wash rows with affected body-part objects."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-178: reflexive wash rows with selected body-part affected S."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-178: affected body-part bite 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-178-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 136 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 Rule 135 body-part senses plus bajaybajay, junkurr, yalbay, bajaku, "
            "kaka, marral, and ngulkurr; excluded waba, jandal, dakil, locational jibarr, and Rule 133/134 support heads. "
            "Syntax checked appositional states, perception, transitive wash, reflexive wash, and 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 locational jibarr, no malbin/jiba/bangkarr/minya, "
            "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 136 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_178.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 136 targets, participants, predicates, verbs, and pronouns.",
        artifact_path="batch_scripts/close_178.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 178: 50 accepted Rule 136 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_178.py",
        artifact_path="batch_scripts/close_178.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-178-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())
