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

NOTES = (
    "HANDLED-OBJECT LEXICAL EXPANSION AFTER RULE 136 (Rule 137). 50 rows. TARGETS: badur hook/line, "
    "karra rope, makarr fish net, ngunyin dilly bag, wangal boomerang, warrbi axe, kunjuri shield, "
    "kalka spear. SUPPORT: balji/balji-nga bag LOC, bubu-ngu ground LOC, bubu-muny ground ABL, "
    "wabarr-ba shade LOC, bayan-ba camp/house LOC, wuna-y lie, nyaji-l see/perceive, yijarri-l put/place, "
    "bawa-l leave, mani-l get/take. REVIEW: balji is support only; no target case forms, instruments, "
    "comitatives, possessives, temporal clitics, body-part traps, Rule 133/134 carry-over heads, jungkalu, "
    "juku, kulji, kambi, or unsourced analogies. Warrbi is axe only, ngunyin dilly bag only, wangal boomerang "
    "noun only; common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "When a needed support noun also looks like a lexical target, demote it explicitly; Rule 137 made `balji` support-only so `balji-nga` did not count as target morphology.", "Rule 137: support-target separation."),
    ("process", "Exact duplicate preflight found `Karra balji-nga wunan` already in Batch 149; the row was repaired before banking rather than accepted as near-new.", "Rule 137: duplicate repair."),
    ("process", "Handled-object expansion should avoid the instrument/comitative temptation even when targets are tools; keep them as bare themes until a sourced instrumental batch is intentionally opened.", "Rule 137: no instrument drift."),
    ("lexicon", "`badur` was selected only as hook and line/fishing line; no `badur-iji` fishing action or `badur-ubu` instrument/source form entered the batch.", "Rule 137: badur."),
    ("lexicon", "`karra` was selected as rope/cord/string; the batch did not use its broader string-like analogies.", "Rule 137: karra."),
    ("lexicon", "`makarr` stayed fish net; the batch avoided generic net-making or catching scenes beyond bare object/location frames.", "Rule 137: makarr."),
    ("lexicon", "`ngunyin` stayed dilly bag only; bark, spider web, and placenta senses were excluded.", "Rule 137: ngunyin."),
    ("lexicon", "`wangal` stayed boomerang noun only; dance-verb drift was excluded.", "Rule 137: wangal."),
    ("lexicon", "`warrbi` stayed axe only; the grass-house sense was excluded.", "Rule 137: warrbi."),
    ("lexicon", "`kunjuri` stayed shield; no weapon-use scene or instrument frame was opened.", "Rule 137: kunjuri."),
    ("lexicon", "`kalka` stayed spear/fishing spear; no `kalka-ji` comitative or `kalka-bu` instrument appeared.", "Rule 137: kalka."),
    ("lexicon", "`balji` was used as bag/container support, chiefly `balji-nga`, and not as a Rule 137 target head.", "Rule 137: balji support."),
    ("morphology", "All selected target heads stayed bare; no dative, locative, ablative, instrumental, comitative, possessive, or compound target form appeared.", "Rule 137: target case restraint."),
    ("morphology", "The only local-case support forms admitted were `balji-nga`, `bubu-ngu`, `wabarr-ba`, `bayan-ba`, and `bubu-muny`.", "Rule 137: support case whitelist."),
    ("morphology", "Common-noun A in perception, placement, leaving, and getting rows was ERG-marked; pronoun A rows stayed bare.", "Rule 137: A marking."),
    ("syntax", "State rows used simple noun-predicate clauses; rest rows used target subject plus a sourced locative support NP plus `wunan`.", "Rule 137: state/rest syntax."),
    ("syntax", "Perception and placement rows used A object location verb order with the target as bare object.", "Rule 137: transitive object-location syntax."),
    ("syntax", "Leave/get rows kept target objects as themes and local phrases as ordinary location/source complements.", "Rule 137: leave/get syntax."),
    ("fidelity", "English labels narrow polysemy instead of expanding it: hook and line, fish net, dilly bag, boomerang, axe, shield, and spear.", "Rule 137: selected-sense fidelity."),
    ("fidelity", "The English phrase 'in the bag' corresponds only to support `balji-nga`; it does not promote `balji` to a target or infer a new case form for target heads.", "Rule 137: container fidelity."),
    ("register", "The batch stays practical and ordinary: objects are good/dry/big, lying somewhere, seen, put, left, or taken.", "Rule 137: register scope."),
    ("handoff", "Next cadence should consolidate these object heads in adjacent but still non-instrumental frames unless a fresh source pass intentionally opens instrument/comitative grammar.", "Rule 137: next cadence."),
]

LEXEMES = [
    ("badur", "noun", None, "NA", "hook; hook and line; fishing line", "batch-179: selected hook-and-line/fishing-line object sense only."),
    ("karra", "noun", None, "NA", "rope; cord; string", "batch-179: selected rope/cord/string object sense."),
    ("makarr", "noun", None, "NA", "fish net", "batch-179: fish-net object sense only."),
    ("ngunyin", "noun", None, "NA", "dilly bag", "batch-179: selected dilly-bag sense only; bark/spider/placenta senses excluded."),
    ("wangal", "noun", None, "NA", "boomerang", "batch-179: boomerang noun only; not dance."),
    ("warrbi", "noun", None, "NA", "axe", "batch-179: axe sense only; grass-house sense excluded."),
    ("kunjuri", "noun", None, "NA", "shield", "batch-179: shield object sense."),
    ("kalka", "noun", None, "NA", "spear; fishing spear", "batch-179: spear/fishing-spear object sense; no kalka-ji or kalka-bu."),
    ("balji", "noun", None, "NA", "bag; dilly bag", "batch-179: support-only container noun, especially balji-nga bag LOC."),
    ("bubu", "noun", None, "NA", "ground; place; country", "batch-179: support local forms bubu-ngu ground LOC and bubu-muny ground ABL."),
    ("wabarr", "noun", None, "NA", "shade", "batch-179: support locative wabarr-ba shade LOC."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-179: support locative bayan-ba camp/house LOC."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-179: state predicate for handled objects."),
    ("marral", "adjective", None, "NA", "dry", "batch-179: state predicate for handled objects."),
    ("yalbay", "adjective", None, "NA", "big", "batch-179: state predicate for handled objects."),
    ("wuna-y", "intransitive-verb", "y", "NA", "lie down", "batch-179: rest/location rows with past wunan."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-179: perception rows with common-noun A ERG and pronoun A bare."),
    ("yijarri-l", "verb", "l", "NA", "put; place", "batch-179: placement rows with target object plus local complement."),
    ("bawa-l", "verb", "l", "NA", "leave; leave alone", "batch-179: leave rows with target object plus local complement."),
    ("mani-l", "transitive-verb", "l", "NA", "get; take", "batch-179: get/take rows with bubu-muny source."),
    ("ngamu", "noun", None, "NA", "mother", "batch-179: common-noun A in object rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-179: common-noun A in object rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-179: common-noun A in object rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-179: common-noun A in object rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-179: common-noun A in object rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-179: common-noun A in object rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-179: common-noun A in object rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-179: bare pronoun A in object rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-179: bare pronoun A in object rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-179: bare pronoun A in object 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-179-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 137 rows. Morphology checked bare targets, allowed support "
            "local forms only, no instruments/comitatives/possessives/temporal clitics, common-noun A ERG, and "
            "pronoun A bare. Lexicon checked badur, karra, makarr, ngunyin, wangal, warrbi, kunjuri, and kalka "
            "selected senses, with balji support-only. Syntax checked state, rest-location, perception, placement, "
            "leave, and get/source frames. Fidelity checked selected-sense English and container support. 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 target case forms, no instruments, no comitatives, no possessive suffixes, "
            "no temporal clitics, no waba/jandal/dakil/jibarr, no malbin/jiba/bangkarr/minya, no jungkalu/juku/"
            "kulji/kambi, no warrbi grass-house sense, no ngunyin bark/spider/placenta sense, and no wangal dance sense."
        ),
        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 137 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_179.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 137 targets, support heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_179.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 179: 50 accepted Rule 137 handled-object lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_179.py",
        artifact_path="batch_scripts/close_179.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-179-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())
