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

NOTES = (
    "IMPLEMENTS/MATERIALS LEXICAL EXPANSION AFTER RULE 148 (Rule 149). 50 rows. TARGETS: kalka spear, naybu knife, "
    "waymbil axe, karra rope, makarr fish net, yinba fish spear, balur spear-thrower, kulji stone, juku wood/material, "
    "juwal digging stick. FRAMES: state/location nominal clauses, bare past perception, support-locative past "
    "perception, present perception. REVIEW: object names and selected senses only; no cutting, spearing, sharpening, "
    "hitting, catching, throwing, tying, making, scraping, poking, killing, fish-catch semantics, target case forms, "
    "instrument morphology, possessives, compounds, juku tree ecology, juwal yam sense, or cultural/weapon-use inference."
)

LESSONS = [
    ("process", "An implement lexical pass can add object-name coverage without opening the action verbs normally associated with those objects.", "Rule 149: names before actions."),
    ("process", "Rule 149 required a stricter English denylist because target nouns like spear and fish spear are allowed, while spearing actions are not.", "Rule 149: noun/action distinction."),
    ("process", "Exact duplicate preflight rejected three initial surfaces and the final plan had 50 unique non-duplicate surfaces.", "Rule 149: duplicate repair before banking."),
    ("lexicon", "`kalka` was selected as spear noun only; no spear-making, comitative, or spearing row.", "Rule 149: kalka noun only."),
    ("lexicon", "`naybu` was selected as knife noun only; no cutting, sharpening, or instrument row.", "Rule 149: naybu noun only."),
    ("lexicon", "`waymbil` was selected as axe noun only; no chopping, cutting, or scraping row.", "Rule 149: waymbil noun only."),
    ("lexicon", "`karra` was selected as rope/cord/string noun only; no tying/coiling/dragging row.", "Rule 149: karra noun only."),
    ("lexicon", "`makarr` was selected as fish-net noun only; no catching, gathering, or fishing-success row.", "Rule 149: makarr noun only."),
    ("lexicon", "`yinba` was selected as fish-spear noun only; no spearing or instrument row.", "Rule 149: yinba noun only."),
    ("lexicon", "`balur` was selected as spear-thrower noun only; no throwing or weapon-use row.", "Rule 149: balur noun only."),
    ("lexicon", "`kulji` was selected as stone noun only; no dropping, throwing, killing, pounding, or instrument row.", "Rule 149: kulji noun only."),
    ("lexicon", "`juku` was selected as wood/material only in Rule 149; no tree ecology or action row.", "Rule 149: juku selected sense."),
    ("lexicon", "`juwal` was selected as digging stick only; the yam sense remained closed.", "Rule 149: juwal selected sense."),
    ("morphology", "All target heads remained bare with no target locative, dative, ablative, instrumental, comitative, possessive, or compound morphology.", "Rule 149: target case restraint."),
    ("morphology", "No target `-bu` instrument forms were admitted, even where Patz examples source them.", "Rule 149: no instrument forms."),
    ("morphology", "Support locatives stayed limited to `madja-nga`, `ngalkal-ba`, `bayan-ba`, and `bubu-ngu`.", "Rule 149: support locative limit."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 149: A marking."),
    ("syntax", "State/location nominal clauses used bare target plus adjective or approved support locative.", "Rule 149: nominal syntax."),
    ("syntax", "Bare past perception rows used `nyajin` with bare implement/material objects.", "Rule 149: bare past perception syntax."),
    ("syntax", "Support-locative past perception rows used `nyajin` plus one approved support locative.", "Rule 149: located past perception syntax."),
    ("syntax", "Present perception rows used `nyajil` with bare implement/material objects.", "Rule 149: present perception syntax."),
    ("fidelity", "English labels selected object names and did not import associated action, tool-use, fishing, hunting, or weapon semantics.", "Rule 149: selected-sense fidelity."),
    ("fidelity", "Polysemy traps stayed closed: `juku` as wood/material only here, and `juwal` as digging stick only.", "Rule 149: polysemy discipline."),
    ("register", "Rows remained plain object descriptions and perception statements, not procedural or cultural claims.", "Rule 149: register scope."),
    ("handoff", "Next cadence should consolidate this implement/material field before any separate action verb field is opened.", "Rule 149: next cadence."),
]

LEXEMES = [
    ("kalka", "noun", None, "NA", "spear", "batch-191: spear noun only; no spearing, making, comitative, or use row."),
    ("naybu", "noun", None, "NA", "knife", "batch-191: knife noun only; no cutting, sharpening, or instrument row."),
    ("waymbil", "noun", None, "NA", "axe", "batch-191: axe noun only; no chopping, cutting, or scraping row."),
    ("karra", "noun", None, "NA", "rope; cord; string", "batch-191: rope noun only; no tying/coiling/dragging row."),
    ("makarr", "noun", None, "NA", "fish net", "batch-191: fish-net noun only; no catching/gathering/fishing-success row."),
    ("yinba", "noun", None, "NA", "fish spear", "batch-191: fish-spear noun only; no spearing or instrument row."),
    ("balur", "noun", None, "NA", "spear-thrower", "batch-191: spear-thrower noun only; no throwing or weapon-use row."),
    ("kulji", "noun", None, "NA", "stone; rock", "batch-191: stone noun only; no throwing/killing/pounding/instrument row."),
    ("juku", "noun", None, "NA", "tree; wood", "batch-191: selected as wood/material; no tree ecology/action row."),
    ("juwal", "noun", None, "NA", "digging stick; yam", "batch-191: selected as digging stick only; yam sense closed."),
    ("dudu", "adjective", None, "NA", "blunt", "batch-191: blunt predicate only, no sharpening/causative row."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-191: object-state predicate only."),
    ("yalbay", "adjective", None, "NA", "big", "batch-191: object-size predicate only."),
    ("madja", "noun", None, "NA", "scrub; rainforest", "batch-191: support-only locative madja-nga."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-191: support-only locative ngalkal-ba."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-191: support-only locative bayan-ba."),
    ("bubu", "noun", None, "NA", "ground; country; place", "batch-191: support-only locative bubu-ngu."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-191: past and present perception rows with implement/material objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-191: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-191: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-191: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-191: bare pronoun A in perception 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-191-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 149 rows. Morphology checked bare implement/material targets, "
            "no target case morphology, no instruments/comitatives/possessives, approved support locatives only, "
            "common-noun A ERG, and pronoun A bare. Lexicon checked selected senses including juku wood/material and "
            "juwal digging-stick-only. Syntax checked state/location nominal, bare past perception, located past "
            "perception, and present perception frames. Fidelity checked action/use exclusions. Register stayed plain."
        ),
        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 cutting/spearing/sharpening/hitting/catching/throwing/tying/making/scraping/"
            "poking/killing row, no target instrument form, no target case form, no possessive or compound target, no "
            "juku tree ecology row, no juwal yam row, no fish-catch row, and no cultural/weapon-use inference."
        ),
        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 149 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_191.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 149 targets, predicates, support heads, verb, participants, and pronouns.",
        artifact_path="batch_scripts/close_191.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 191: 50 accepted Rule 149 implement/material lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_191.py",
        artifact_path="batch_scripts/close_191.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 detail LIKE '%batch-191:%'").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, {lesson_count} lessons, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_review_remaining}, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
