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

NOTES = (
    "CONSTRUCTION: CONSOLIDATION AFTER RULE 133 (Rule 134). 50 rows. DESIGN: hand-authored construction "
    "consolidation reusing the Rule 133 animal/body-flesh heads in old state, perception, food/object, want/ask, "
    "transfer, wash/reflexive wash, affected-object, and rest-location frames. SOURCE CONTROLS: Rule 133 dictionary "
    "and grammar readback, Batch 175 surface readback, static guards, and exact duplicate scan. REVIEW: no dakil, "
    "front-leg, or hind-leg rows; malbin upper leg only with no case forms; jiba literal liver only; bangkarr "
    "body/flesh only; minya meat/flesh-food only; no instruments, comitatives, possessives, temporal clitics, or "
    "unsourced analogies; common-noun A ERG, pronoun A bare, babaji-y asker unmarked."
)

LESSONS = [
    ("process", "A construction consolidation after a lexical pass should re-use the new heads in old frames, not add another noun field.", "Rule 134: construction cadence."),
    ("process", "Batch 176 kept exact duplicate scanning as a pre-bank blocker; no planned surfaces duplicated the accepted corpus.", "Rule 134: duplicate guard."),
    ("process", "The process log records selected and excluded senses again even though Rule 133 already did; construction batches can drift unless the traps are repeated.", "Rule 134: repeated source controls."),
    ("lexicon", "`bajibay` remained literal bone in state, perception, eating, placement, leaving, want/ask, transfer, and rest rows.", "Rule 134: bajibay."),
    ("lexicon", "`bangkarr` remained body/flesh, not steak or meat-classifier; it occurred in state, perception, and wash rows only.", "Rule 134: bangkarr."),
    ("lexicon", "`biji` remained animal tail in `kuyu biji` and `kaya biji` whole-part appositions.", "Rule 134: biji."),
    ("lexicon", "`jiba` remained literal liver; no `jiba-badi` or other emotional compound entered the rows.", "Rule 134: jiba."),
    ("lexicon", "`malbin` remained upper leg only; `dakil`, front-leg, and hind-leg wording were excluded again.", "Rule 134: malbin/dakil."),
    ("lexicon", "`minya` support rows used meat/flesh-food only, and `kuyu` support rows used fish only.", "Rule 134: support heads."),
    ("morphology", "No new `malbin` case form was admitted; `malbin` stayed bare in state, perception, wash, reflexive wash, and affected-object rows.", "Rule 134: malbin case restraint."),
    ("morphology", "No instrument, comitative, alienable possessive, temporal clitic, or unapproved dative form appeared.", "Rule 134: no extra morphology."),
    ("morphology", "Dative topics stayed inside the source-backed set: `jiba-ka`, `bajibay-ngka`, `kuyu-ku`, `minya-ka`, and `bajibay-kari-ka`.", "Rule 134: dative bounds."),
    ("syntax", "Common-noun agents in perception, eating, cooking, placement, leaving, getting, giving, wash, and bite rows were ERG-marked.", "Rule 134: common-noun A."),
    ("syntax", "Pronoun A rows stayed bare in perception, leaving, want, and reflexive wash rows.", "Rule 134: pronoun A."),
    ("syntax", "`babaji-y` ask-about rows kept the asker unmarked, the person as LOC:pt, and the topic as DAT.", "Rule 134: ask-about frame."),
    ("syntax", "Whole-part apposition remained bare: `kuyu biji`, `kaya biji`, person plus `malbin`, and person plus `bangkarr`.", "Rule 134: whole-part apposition."),
    ("fidelity", "English possessive phrasing did not introduce Kuku possessive suffixes; the Kuku remains inalienable apposition.", "Rule 134: possessive English."),
    ("fidelity", "All food rows were literal food/object scenes; no metaphorical, symbolic, or weak-source meanings were introduced.", "Rule 134: literal fidelity."),
    ("register", "The batch stays practical and ordinary: body states, seeing, eating, cooking, putting, leaving, taking, wanting, asking, giving, washing, biting, and lying.", "Rule 134: register scope."),
    ("handoff", "Next cadence should return to lexical expansion only after a fresh source pass; do not let Rule 133 traps expire.", "Rule 134: next cadence."),
]

LEXEMES = [
    ("bajibay", "noun", None, "NA", "bone", "batch-176: construction consolidation retained literal bone only across old frames."),
    ("bangkarr", "noun", None, "NA", "body; flesh", "batch-176: body/flesh only; steak drift excluded again."),
    ("biji", "noun", None, "NA", "tail", "batch-176: tail only in animal whole-part apposition."),
    ("jiba", "noun", None, "NA", "liver", "batch-176: literal liver only; emotional compounds excluded."),
    ("malbin", "noun", None, "NA", "upper leg", "batch-176: upper leg only; no dative, locative, instrumental, or comitative forms."),
    ("minya", "noun", None, "NA", "meat; flesh food", "batch-176: support head meat/flesh-food only."),
    ("kuyu", "noun", None, "NA", "fish", "batch-176: support head fish only, including kuyu biji tail rows."),
    ("jiba-ka", "case-form", None, "DAT", "for/about liver", "batch-176: retained source-backed liver dative."),
    ("bajibay-ngka", "case-form", None, "DAT", "for/about a bone", "batch-176: retained bone dative in want/ask rows."),
    ("minya-ka", "case-form", None, "DAT", "for/about meat", "batch-176: retained meat dative in boneless-meat phrase."),
    ("kuyu-ku", "case-form", None, "DAT", "for/about fish", "batch-176: retained fish dative in want/ask rows."),
    ("bajibay-kari", "adjective", None, "NA", "boneless; without bones", "batch-176: retained privative bone-less adjective."),
    ("bajibay-kari-ka", "case-form", None, "DAT", "for/about boneless", "batch-176: retained dative privative modifier."),
    ("nyaji-l", "verb", "l", "NA", "see; perceive", "batch-176: perception rows with common-noun A ERG and pronoun A bare."),
    ("nuka-l", "verb", "l", "NA", "eat; consume", "batch-176: eating rows with bone and liver."),
    ("waju-l", "verb", "l", "NA", "cook; burn", "batch-176: cooking rows with boneless meat and fish."),
    ("yijarri-l", "verb", "l", "NA", "put; place", "batch-176: placement rows with liver and bone."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-176: leave rows with liver and bone."),
    ("mani-l", "verb", "l", "NA", "get; take", "batch-176: get/take rows with liver and meat."),
    ("daya", "transitive-verb", None, "NA", "give", "batch-176: past dajin transfer rows with bone and liver."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-176: ask-about rows with unmarked S, person LOC:pt, topic DAT."),
    ("julurri-l", "verb", "l", "NA", "wash", "batch-176: transitive wash rows with malbin and bangkarr."),
    ("julurri-ji-y", "verb", "y", "NA", "wash oneself", "batch-176: reflexive wash row with malbin."),
    ("bayka-l", "verb", "l", "NA", "bite", "batch-176: bite rows with malbin and kuyu biji."),
    ("wuna-y", "intransitive-verb", "y", "NA", "lie; be lying", "batch-176: rest-location rows with bone, liver, fish-tail, and boneless meat."),
    ("kaka", "adjective", None, "NA", "sore; pain", "batch-176: upper-leg/body soreness only."),
    ("marral", "adjective", None, "NA", "dry", "batch-176: dry state rows with body, tail, and liver."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-176: good state rows with upper leg, fish tail, bone, and boneless meat."),
    ("bajaku", "degree", None, "NA", "very", "batch-176: degree particle in bone state row."),
    ("yalbay", "adjective", None, "NA", "big", "batch-176: bone size state row."),
    ("kalbay", "adjective", None, "NA", "long", "batch-176: retained from Rule 133 tail state source set; not foregrounded in rows."),
    ("bubu-ngu", "case-form", None, "LOC", "on/in the ground", "batch-176: retained ground LOC."),
    ("bubu-muny", "case-form", None, "ABL", "from the ground", "batch-176: retained ground source."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-176: retained bag LOC."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-176: retained shade LOC."),
    ("ngamu-ndu", "case-form", None, "LOC:pt", "at/to mother", "batch-176: addressee form."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "at/to father", "batch-176: recipient form."),
    ("kami-nda", "case-form", None, "LOC:pt", "at/to grandfather", "batch-176: addressee form."),
    ("karrkay-anda", "case-form", None, "LOC:pt", "at/to child", "batch-176: addressee/recipient form."),
    ("kaya", "noun", None, "NA", "dog", "batch-176: dog as whole for tail and agent in bone/upper-leg rows."),
    ("ngalngal", "noun", None, "NA", "crab", "batch-176: crab bite row."),
    ("bubu", "noun", None, "NA", "ground; country", "batch-176: ground support noun in locative/ablative rows."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-176: bag support noun in location rows."),
    ("wabarr", "noun", None, "NA", "shade", "batch-176: 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-176-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 134 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 "
            "no new malbin case forms. Lexicon checked Rule 133 selected senses and excluded dakil/front-leg/hind-leg, "
            "jiba-badi, bangkarr steak drift, and minya generic-animal rows. Syntax checked whole-part apposition, "
            "perception, food/object transitive rows, ask-about, transfer, wash/reflexive wash, bite, and rest-location "
            "rows. Fidelity checked literal mappings and no possessive import. 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: no new lexical heads, no dakil, no front/hind-leg rows, malbin upper leg only, "
            "jiba literal liver only, bangkarr body/flesh only, 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 134 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_176.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 134 target heads, support heads, case forms, predicates, and support nouns.",
        artifact_path="batch_scripts/close_176.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 176: 50 accepted Rule 134 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_176.py",
        artifact_path="batch_scripts/close_176.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-176-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())
