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

NOTES = (
    "WEAPON/IMPLEMENT REFERENCE LEXICAL EXPANSION AFTER RULE 188 (Rule 189). 50 rows. TARGETS: birungubay "
    "paddle/oar, durray fighting stick, jinil spear barb, kukuni big spear, kulbanmuku axe, kurajan turtle spear "
    "point, kuyan war spear, mirru club, nala-nala waddy club, and ngurmu decorated butt of woomera. FRAMES: bare "
    "yaluy deictic identification, present perception with ngayu, yinyay-supported present perception with yundu, "
    "yinyay-supported past perception with jana, and yaluy-supported present perception with ngana. REVIEW: all "
    "targets stayed bare; no throwing, spearing, cutting, chopping, hitting, killing, hunting, catching, fighting "
    "event, instrumental/comitative/possessive/case morphology, material-source claim, loan import, place-name "
    "homograph, body-part/euphemism drift, target compound, plural derivation, or productive reduplication."
)

LESSONS = [
    ("process", "Rule 189 deliberately selected a bounded weapon/implement reference field after the Rule 188 construction pass.", "Rule 189: lexical cadence after Rule 188."),
    ("process", "The source pass preferred low-hit heads and rejected higher-pressure homograph, loan, use-event, and prior-frequency candidates.", "Rule 189: candidate triage."),
    ("process", "`dikarra` was excluded because Patz also uses it as a place name; the weapon gloss can be revisited only in a targeted homograph sweep.", "Rule 189: dikarra rejection."),
    ("process", "`jindal` was excluded because the spear noun is homophonous with the puncture-bite verb.", "Rule 189: jindal homograph restraint."),
    ("process", "`mirrba` was excluded because its dictionary prose includes rifle extension and sensitive defence/judicial-duel context.", "Rule 189: mirrba restraint."),
    ("process", "`naybu` remains an English loan knife and was not admitted in this native-head lexical pass.", "Rule 189: loan restraint."),
    ("lexicon", "`birungubay` was admitted as paddle/oar only; rowing and travel-event frames stayed closed.", "Rule 189: birungubay."),
    ("lexicon", "`durray` was admitted as fighting stick only; fighting, hitting, and injury events stayed closed.", "Rule 189: durray."),
    ("lexicon", "`jinil` was admitted as spear barb only; spear-use and material-source rows stayed closed.", "Rule 189: jinil."),
    ("lexicon", "`kukuni` was admitted as big spear only; harpoon/turtle-spearing events stayed closed.", "Rule 189: kukuni."),
    ("lexicon", "`kulbanmuku` was admitted as axe only; stone-source, cutting, chopping, and tool-use rows stayed closed.", "Rule 189: kulbanmuku."),
    ("lexicon", "`kurajan` was admitted as the Yalanji turtle spear point form; `biyul` and `kurrajan` stayed outside this batch.", "Rule 189: kurajan."),
    ("lexicon", "`kuyan` was admitted as war spear only; quartz-head material prose stayed closed.", "Rule 189: kuyan."),
    ("lexicon", "`mirru` was admitted as club only; striking and weapon-use rows stayed closed.", "Rule 189: mirru."),
    ("lexicon", "`nala-nala` was admitted as waddy club only; the reduplicated spelling is lexical, not productive reduplication license.", "Rule 189: nala-nala."),
    ("lexicon", "`ngurmu` was admitted as woomera butt only; throwing, woomera-use, and defence prose stayed closed.", "Rule 189: ngurmu."),
    ("morphology", "All Rule 189 target heads stayed bare with zero absolutive object marking.", "Rule 189: bare target morphology."),
    ("morphology", "No target locative, dative, ablative, perlative, ergative, instrumental, comitative, possessive, privative, excess, plural, compound, or productive-reduplicated form was admitted.", "Rule 189: target case restraint."),
    ("morphology", "`nala-nala` stayed a dictionary head with lexical reduplication, not a model for productive target reduplication.", "Rule 189: lexical reduplication distinction."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 189: perception tense forms."),
    ("syntax", "Rows 1-10 used one target noun plus `yaluy` with no predicator.", "Rule 189: yaluy deictic syntax."),
    ("syntax", "Rows 11-20 used bare `ngayu` plus one bare target and present `nyajil`.", "Rule 189: ngayu perception."),
    ("syntax", "Rows 21-30 used bare `yundu`, one bare target, `yinyay`, and present `nyajil`.", "Rule 189: yundu yinyay perception."),
    ("syntax", "Rows 31-40 used bare `jana`, one bare target, `yinyay`, and past `nyajin`.", "Rule 189: jana yinyay past perception."),
    ("handoff", "Next cadence should consolidate the Rule 189 weapon/implement reference field without opening weapon-use, material-source, loan, case, plural, or event semantics.", "Rule 189: next cadence."),
]

LEXEMES = [
    ("birungubay", "noun", None, "NA", "paddle; oar", "batch-231: admitted as paddle/oar only; no rowing or travel-event row."),
    ("durray", "noun", None, "NA", "fighting stick", "batch-231: admitted as fighting stick only; no fighting, hitting, or injury event row."),
    ("jinil", "noun", None, "NA", "barb of spear", "batch-231: admitted as spear barb only; no spear-use or material-source row."),
    ("kukuni", "noun", None, "NA", "big spear; harpoon", "batch-231: admitted as big spear only; no turtle-spearing or harpoon-use row."),
    ("kulbanmuku", "noun", None, "NA", "axe", "batch-231: admitted as axe only; no stone-source, cutting, or chopping row."),
    ("kurajan", "noun", None, "NA", "turtle spear point", "batch-231: admitted as Yalanji turtle spear point only; no turtle event row."),
    ("kuyan", "noun", None, "NA", "war spear", "batch-231: admitted as war spear only; quartz-head source prose closed."),
    ("mirru", "noun", None, "NA", "club", "batch-231: admitted as club only; no striking or weapon-use row."),
    ("nala-nala", "noun", None, "NA", "waddy club", "batch-231: admitted as waddy club only; lexical reduplication not productive license."),
    ("ngurmu", "noun", None, "NA", "decorated butt of woomera", "batch-231: admitted as woomera butt only; no throwing or defence row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-231: retained local demonstrative in deictic and supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-231: retained local demonstrative in supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-231: retained past and nonpast perception rows with weapon/implement nouns."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-231: bare pronoun A in present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-231: bare pronoun A in yinyay-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-231: bare pronoun A in yinyay-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-231: bare pronoun A in yaluy-supported present 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-231-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 by SQL token estimate)",
                 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 189 rows. Morphology checked bare target nouns, no target case/compound/possessive/instrument/comitative/plural/productive-reduplication forms, lexical reduplication restraint for nala-nala, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked the selected dictionary senses and kept rejected candidates, loan heads, weapon-use events, material-source prose, homographs, body-part/euphemism drift, and prior high-frequency heads closed. Syntax checked bare yaluy deictic identification, present perception with ngayu, yinyay-supported present perception with yundu, yinyay-supported past perception with jana, and yaluy-supported present perception with ngana. Fidelity checked no use-event or source-prose import. Register stayed ordinary reference/perception.",
                 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 locative/dative/ablative/perlative/ergative/instrument/comitative/possessive/privative/excess/plural/productive-reduplication/compound form, no loan token, no weapon-use/material-source/body-part/place-name/euphemism drift, and no event claim.",
                 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 189 lessons covering source checks, lexical scope, rejected candidates, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_231.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 189 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_231.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 231: 50 accepted Rule 189 weapon/implement reference lexical expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_231.py", artifact_path="batch_scripts/close_231.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 LIKE 'batch-231%'").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, {lexeme_logs} lexeme/source-log rows, {process_events} process events, under_review={under_review_remaining}, verified corpus={verified}")
    return 0


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