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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 155 (Rule 156). 50 rows. RETAINED TARGETS: kabal Leichhardt tree, "
    "jujabala ironwood tree, kangka wild grape, nganjirr grass tree, junda wild plum, jikan grass, buyku paperbark, "
    "kanunjul grass-tree resin, yibuy loya cane, wukay hairy yam. FRAMES: bare deictic identification with yaluy; "
    "bare present and past perception; yinyay-supported present perception with pronoun and ERG-marked common-noun A. "
    "REVIEW: no new target heads, all targets bare, no target case forms, no compounds, no plant-use predicates, no "
    "medicine preparation, no food-use, no material-source claims, no burning/storm-control claims, and no "
    "carry-forward weather/geography/implement inference."
)

LESSONS = [
    ("process", "A construction consolidation pass after a plant-resource lexical batch should add frame coverage without opening plant-use semantics.", "Rule 156: construction after lexical pass."),
    ("process", "Rule 156 admitted no new target heads and reused only the Rule 155 plant-resource field.", "Rule 156: no-new-target discipline."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 156: duplicate preflight."),
    ("lexicon", "`kabal` stayed Leichhardt tree only; no fruit-finding or medicine row.", "Rule 156: kabal retained scope."),
    ("lexicon", "`jujabala` stayed ironwood tree only; no bark-burning or thunderstorm-control row.", "Rule 156: jujabala retained scope."),
    ("lexicon", "`kangka` stayed wild grape only; no medicinal, vine-use, or storm-control row.", "Rule 156: kangka retained scope."),
    ("lexicon", "`nganjirr` stayed grass tree only; no burning or ritual-use row.", "Rule 156: nganjirr retained scope."),
    ("lexicon", "`junda` stayed wild plum only; no eating, gathering, or fig drift row.", "Rule 156: junda retained scope."),
    ("lexicon", "`jikan` stayed grass only; no walking-through, snake, feed, or burning frame.", "Rule 156: jikan retained scope."),
    ("lexicon", "`buyku` stayed paperbark only; no covering, roof, carrier, or bark-use row.", "Rule 156: buyku retained scope."),
    ("lexicon", "`kanunjul` stayed grass-tree resin only; no burning, pitch-making, binding, storm-control, or smoking-house row.", "Rule 156: kanunjul retained scope."),
    ("lexicon", "`yibuy` stayed loya cane only; no weaving, tying, walking-stick, or material-source row.", "Rule 156: yibuy retained scope."),
    ("lexicon", "`wukay` stayed hairy yam only; no digging, eating, cooking, or searching row.", "Rule 156: wukay retained scope."),
    ("morphology", "All plant-resource target heads stayed bare; no target LOC, DAT, ABL, PERL, INST, COMIT, POSS, or compound morphology appeared.", "Rule 156: target case restraint."),
    ("morphology", "`yaluy` and `yinyay` were support deictics only and were not attached to target heads.", "Rule 156: deictic support restraint."),
    ("morphology", "Common-noun A forms were ERG-marked: ngamu-ngku, nganjan-angka, karrkay-ngku, babi-ngka, kami-ngka, jalbu-ngku, dingkar-angka.", "Rule 156: common-noun A marking."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `ngana`, and `jana` stayed bare.", "Rule 156: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 156: perception tense forms."),
    ("syntax", "Bare deictic-identification rows used one plant-resource target plus `yaluy` and no predicator.", "Rule 156: deictic syntax."),
    ("syntax", "Bare present perception rows used one bare plant-resource object plus `nyajil`.", "Rule 156: present perception syntax."),
    ("syntax", "Bare past perception rows used one bare plant-resource object plus `nyajin`.", "Rule 156: past perception syntax."),
    ("syntax", "`yinyay`-supported present perception rows used one bare target, one support deictic, and `nyajil`.", "Rule 156: yinyay-supported perception syntax."),
    ("fidelity", "English labels selected only source-attested plant-resource senses and did not add action, medicinal, ritual, weather, or material-use inference.", "Rule 156: selected-sense fidelity."),
    ("fidelity", "No plant-use fact from dictionary or Patz prose was imported as a sentence claim.", "Rule 156: no source-event import."),
    ("register", "Rows remained ordinary plant-resource deictic/perception statements.", "Rule 156: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but keep Rule 155-156 plant-use traps closed unless deliberately sourced.", "Rule 156: next cadence."),
]

LEXEMES = [
    ("kabal", "noun", None, "NA", "Leichhardt tree", "batch-198: retained Leichhardt tree only in construction-consolidation rows; no fruit-finding/medicine row."),
    ("jujabala", "noun", None, "NA", "ironwood tree", "batch-198: retained ironwood tree only; no anti-thunderstorm burning row."),
    ("kangka", "noun", None, "NA", "wild grape", "batch-198: retained wild grape only; no medicine/vine-use/storm-control row."),
    ("nganjirr", "noun", None, "NA", "grass tree", "batch-198: retained grass tree only; no burning/ritual-use row."),
    ("junda", "noun", None, "NA", "wild plum", "batch-198: retained wild plum only; no gathering/eating/fig drift row."),
    ("jikan", "noun", None, "NA", "grass", "batch-198: retained grass only; no walking-through/snake/feed/burning frame."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-198: retained paperbark only; no cover/roof/carrier/bark-use row."),
    ("kanunjul", "noun", None, "NA", "grass-tree resin", "batch-198: retained grass-tree resin only; no burning/pitch-binding/storm-control row."),
    ("yibuy", "noun", None, "NA", "loya cane", "batch-198: retained loya cane only; no weaving/tying/walking-stick/material-source row."),
    ("wukay", "noun", None, "NA", "hairy yam", "batch-198: retained hairy yam only; no digging/eating/cooking/searching row."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-198: retained local demonstrative in supported perception rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-198: retained local demonstrative in bare deictic identification rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-198: retained past and nonpast perception rows with plant-resource objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-198: bare pronoun A in perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-198: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-198: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-198: bare pronoun A in perception rows."),
    ("ngamu", "noun", None, "NA", "mother", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-198: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-198: common-noun A in perception rows, ERG-marked."),
]


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-198-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 156 rows. Morphology checked bare plant-resource targets, no target case/compound forms, yinyay/yaluy support only, common-noun A ERG, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected plant-resource senses. Syntax checked bare deictic identification, bare present perception, bare past perception, yinyay-supported present perception, second-person perception, and common-noun A perception. Fidelity checked no plant-use/medicine/material-source/weather import. 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 new target head, no target locative/dative/ablative/perlative/instrument/comitative/possessive/compound form, no digging/eating/gathering/burning/scraping/chopping/weaving/tying/cooking row, no medicine/resin/bark-use/material-source row, and no carry-forward weather/geography/implement semantics.",
                 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 156 lessons covering process, retained lexical senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_198.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 156 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_198.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 198: 50 accepted Rule 156 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_198.py", artifact_path="batch_scripts/close_198.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-198:%'").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())
