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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 137 (Rule 138). 50 rows. TARGETS RETAINED: badur hook/line, "
    "karra rope, makarr fish net, ngunyin dilly bag, wangal boomerang, warrbi axe, kunjuri shield, kalka spear. "
    "DESIGN: no new lexical field; recombined Rule 137 heads in state, rest-location, perception, placement, "
    "leave, and get/source frames. SUPPORT: balji-nga bag LOC, bubu-ngu ground LOC, bubu-muny ground ABL, "
    "wabarr-ba shade LOC, bayan-ba camp/house LOC. REVIEW: balji 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 polysemy drift; warrbi axe only, ngunyin dilly bag only, wangal boomerang noun only; "
    "common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "A construction pass after Rule 137 should recombine the same handled-object heads rather than admitting another object/tool field.", "Rule 138: construction cadence."),
    ("process", "Rule 138 repeated the source readback and exact duplicate scan, because high-frequency object frames had already consumed many simple surfaces.", "Rule 138: duplicate vigilance."),
    ("process", "Constructional variety came from participant/location recombination, not morphology expansion.", "Rule 138: conservative variety."),
    ("lexicon", "`badur` stayed hook and line/fishing line; no fishing-action or instrument/source form entered.", "Rule 138: badur."),
    ("lexicon", "`karra` stayed rope/cord/string; no broad string-like analogy was opened.", "Rule 138: karra."),
    ("lexicon", "`makarr` stayed fish net; no generic net-making or catching scene was opened.", "Rule 138: makarr."),
    ("lexicon", "`ngunyin` stayed dilly bag only; bark, spider-web, and placenta senses were excluded again.", "Rule 138: ngunyin."),
    ("lexicon", "`wangal` stayed boomerang noun only; dance drift was excluded again.", "Rule 138: wangal."),
    ("lexicon", "`warrbi` stayed axe only; grass-house sense was excluded again.", "Rule 138: warrbi."),
    ("lexicon", "`kunjuri` stayed shield; no weapon-use or instrument frame was opened.", "Rule 138: kunjuri."),
    ("lexicon", "`kalka` stayed spear/fishing spear; no `kalka-ji` or `kalka-bu` appeared.", "Rule 138: kalka."),
    ("lexicon", "`balji` remained support-only, chiefly as `balji-nga` bag LOC.", "Rule 138: balji support."),
    ("morphology", "All target heads stayed bare; no dative, locative, ablative, instrumental, comitative, possessive, or compound target form appeared.", "Rule 138: target case restraint."),
    ("morphology", "The only support local forms were `balji-nga`, `bubu-ngu`, `wabarr-ba`, `bayan-ba`, and `bubu-muny`.", "Rule 138: support case whitelist."),
    ("morphology", "Common-noun A in perception, placement, leaving, and getting rows was ERG-marked; pronoun A rows stayed bare.", "Rule 138: A marking."),
    ("syntax", "State rows stayed as simple noun-predicate clauses with already verified predicates.", "Rule 138: state syntax."),
    ("syntax", "Rest rows kept target subject plus one sourced local complement plus `wunan`.", "Rule 138: rest syntax."),
    ("syntax", "Transitive object-location rows kept the target as a bare object and the support phrase as location/source.", "Rule 138: transitive object-location syntax."),
    ("fidelity", "English labels again narrow the polysemy: hook and line, rope, fish net, dilly bag, boomerang, axe, shield, and spear.", "Rule 138: selected-sense fidelity."),
    ("fidelity", "Rows with `balji-nga` express a support container location only and do not promote `balji` to a target.", "Rule 138: support fidelity."),
    ("register", "The batch stays ordinary and practical: objects are good/dry, lying somewhere, seen, put, left, or taken.", "Rule 138: register scope."),
    ("handoff", "Next cadence may return to lexical expansion only after a fresh source pass; keep Rule 137/138 instrument and polysemy traps active.", "Rule 138: next cadence."),
]

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