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

NOTES = (
    "LEXICAL EXPANSION AFTER RULE 144 (Rule 145). 50 rows. TARGETS: kuyu fish, ngawiya sea turtle, ngujay freshwater "
    "turtle, bilngkumu saltwater crocodile, kubarr freshwater eel, yawu stingray, yaburr shark, kiju mud crab, "
    "ngalngal sand crab. FRAMES: state, water-location nominal clauses, past perception, present perception. REVIEW: "
    "no catching/spearing/hooking/netting, no cooking/roasting/stewing/eating, no meat/food, no taboo/storm/rain, no "
    "fear/biting/illness, no story/myth/totem claims, no target case forms, no instruments, no comitatives, no "
    "possessives, no compounds; ngiwa excluded; common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "A water-fauna lexical pass should name animals first and defer catching, spearing, cooking, eating, taboo, and story ecology to separately sourced passes.", "Rule 145: name-first sequence."),
    ("process", "`Ngiwa` was excluded because dictionary senses include moray eel, sea snake, place, and story-site readings.", "Rule 145: ngiwa exclusion."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 145: duplicate preflight."),
    ("lexicon", "`kuyu` selected generic fish.", "Rule 145: kuyu."),
    ("lexicon", "`ngawiya` selected sea turtle using dictionary spelling; Patz `ngawuya` noted as a variant/example spelling.", "Rule 145: ngawiya."),
    ("lexicon", "`ngujay` selected freshwater turtle only.", "Rule 145: ngujay."),
    ("lexicon", "`bilngkumu` selected saltwater crocodile only; fear, biting, dream, and story rows stayed closed.", "Rule 145: bilngkumu."),
    ("lexicon", "`kubarr` selected big black freshwater eel only; cooking, eating, and sickness rows stayed closed.", "Rule 145: kubarr."),
    ("lexicon", "`yawu` selected stingray only; spearing, storm, rain, and taboo rows stayed closed.", "Rule 145: yawu."),
    ("lexicon", "`yaburr` selected shark only; biting rows stayed closed.", "Rule 145: yaburr."),
    ("lexicon", "`kiju` selected mud crab only; fear/nip rows stayed closed.", "Rule 145: kiju."),
    ("lexicon", "`ngalngal` selected sand crab and stayed a whole reduplicated lexical head.", "Rule 145: ngalngal."),
    ("morphology", "All water-fauna target heads stayed bare; no target dative, locative, ablative, instrumental, comitative, possessive, or compound forms appeared.", "Rule 145: target case restraint."),
    ("morphology", "The only support local form was `bana-nga`; `bana` remained a support head, not a target.", "Rule 145: support form limit."),
    ("morphology", "`Ngalngal` was treated as a whole lexical crab head, not productive reduplication.", "Rule 145: lexical reduplication."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 145: A marking."),
    ("syntax", "State rows stayed simple noun-predicate clauses using `ngulkurr` and `yalbay`.", "Rule 145: state syntax."),
    ("syntax", "Water-location rows used bare nominal clauses with `bana-nga` water LOC.", "Rule 145: location syntax."),
    ("syntax", "Past perception rows used `nyajin` with bare fauna objects and optional water location.", "Rule 145: past perception syntax."),
    ("syntax", "Present perception rows used `nyajil` with bare fauna objects.", "Rule 145: present perception syntax."),
    ("fidelity", "English labels explicitly name selected water-fauna senses, especially saltwater crocodile, sea turtle, freshwater turtle, freshwater eel, mud crab, and sand crab.", "Rule 145: selected-sense fidelity."),
    ("fidelity", "No row imported catching, spearing, hooking, netting, cooking, roasting, stewing, eating, meat, food, taboo, storm, rain, fear, biting, illness, story, myth, or totem inference.", "Rule 145: no ecology inference."),
    ("register", "Rows remained ordinary descriptions of water fauna being good/big, being in water, or being seen.", "Rule 145: register scope."),
    ("handoff", "Next cadence should normally consolidate these water-fauna heads before opening fishing/cooking/taboo/story ecology.", "Rule 145: next cadence."),
    ("handoff", "Carry forward `ngiwa` exclusion and `yawu` storm/spearing trap in the next bank script.", "Rule 145: carry-forward traps."),
]

LEXEMES = [
    ("kuyu", "noun", None, "NA", "fish", "batch-187: selected generic fish."),
    ("ngawiya", "noun", None, "NA", "sea turtle", "batch-187: selected sea turtle using dictionary spelling; Patz examples also show ngawuya."),
    ("ngujay", "noun", None, "NA", "freshwater turtle", "batch-187: selected freshwater turtle only."),
    ("bilngkumu", "noun", None, "NA", "saltwater crocodile", "batch-187: selected saltwater crocodile only; fear/biting/story rows not opened."),
    ("kubarr", "noun", None, "NA", "big black freshwater eel", "batch-187: selected freshwater eel only; cooking/eating/sickness rows not opened."),
    ("yawu", "noun", None, "NA", "stingray", "batch-187: selected stingray only; storm/rain/spearing/taboo rows not opened."),
    ("yaburr", "noun", None, "NA", "shark", "batch-187: selected shark only; biting rows not opened."),
    ("kiju", "noun", None, "NA", "mud crab", "batch-187: selected mud crab only; fear/nip rows not opened."),
    ("ngalngal", "noun", None, "NA", "sand crab", "batch-187: selected sand crab; whole reduplicated lexical head."),
    ("ngiwa", "noun", None, "NA", "moray eel; sea snake; place/story-site", "batch-187: excluded because senses are unstable for this narrow pass."),
    ("bana", "noun", None, "NA", "water", "batch-187: support-only location in bana-nga water LOC."),
    ("ngulkurr", "adjective", None, "NA", "good", "batch-187: state predicate for water-fauna rows."),
    ("yalbay", "adjective", None, "NA", "big", "batch-187: state predicate for water-fauna rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-187: past and present perception rows with water-fauna objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-187: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-187: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-187: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-187: 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-187-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 145 rows. Morphology checked bare water-fauna targets, no "
            "target case morphology, no instruments/comitatives/possessives, support-only bana-nga, common-noun A ERG, "
            "and pronoun A bare. Lexicon checked selected water-fauna senses and excluded ngiwa. Syntax checked state, "
            "water-location nominal clauses, past perception, and present perception frames. Fidelity checked ecology "
            "exclusions. 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 catching/spearing/hooking/netting row, no cooking/roasting/stewing/eating row, "
            "no meat/food row, no taboo/storm/rain row, no fear/biting/illness row, no story/myth/totem claim, no target "
            "instrument row, no target case form, no unresolved ngiwa row, and no carry-forward bird/tree/fire drift."
        ),
        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 145 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_187.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 145 targets, excluded candidates, support heads, predicates, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_187.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 187: 50 accepted Rule 145 water-fauna lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_187.py",
        artifact_path="batch_scripts/close_187.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-187:%'").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())
