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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 145 (Rule 146). 50 rows. TARGETS RETAINED: 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: past perception, past perception with bana-nga water LOC, present "
    "perception. REVIEW: no new target heads, 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 still excluded; common-noun A ERG, "
    "pronoun A bare."
)

LESSONS = [
    ("process", "A construction pass after water-fauna lexical expansion can safely strengthen A-marking, water-location support, and present/past perception without opening fishing ecology.", "Rule 146: construction before ecology."),
    ("process", "`Ngiwa` remained excluded because moray eel, sea-snake, place, and story-site senses are unstable for this narrow field.", "Rule 146: ngiwa remains excluded."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 146: duplicate preflight."),
    ("lexicon", "`kuyu` remained generic fish.", "Rule 146: kuyu retained."),
    ("lexicon", "`ngawiya` remained sea turtle using dictionary spelling.", "Rule 146: ngawiya retained."),
    ("lexicon", "`ngujay` remained freshwater turtle only.", "Rule 146: ngujay retained."),
    ("lexicon", "`bilngkumu` remained saltwater crocodile only; dream, story, fear, and biting rows stayed closed.", "Rule 146: bilngkumu retained."),
    ("lexicon", "`kubarr` remained freshwater eel only; cooking, eating, and sickness rows stayed closed.", "Rule 146: kubarr retained."),
    ("lexicon", "`yawu` remained stingray only; spearing, storm, rain, and taboo rows stayed closed.", "Rule 146: yawu retained."),
    ("lexicon", "`yaburr` remained shark only; biting rows stayed closed.", "Rule 146: yaburr retained."),
    ("lexicon", "`kiju` remained mud crab only; fear/nip rows stayed closed.", "Rule 146: kiju retained."),
    ("lexicon", "`ngalngal` remained a whole sand-crab lexical head.", "Rule 146: ngalngal retained."),
    ("morphology", "All water-fauna target heads stayed bare; no target dative, locative, ablative, instrumental, comitative, possessive, or compound forms appeared.", "Rule 146: target case restraint."),
    ("morphology", "The only support local form was `bana-nga`; `bana` remained a support head, not a target.", "Rule 146: support form limit."),
    ("morphology", "`Ngalngal` was treated as a whole lexical crab head, not productive reduplication.", "Rule 146: lexical reduplication."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 146: A marking."),
    ("syntax", "Past perception rows used `nyajin` with bare fauna objects.", "Rule 146: past perception syntax."),
    ("syntax", "Water-location perception rows used `nyajin` plus support-only `bana-nga`.", "Rule 146: water-location perception syntax."),
    ("syntax", "Present perception rows used `nyajil` with bare fauna objects.", "Rule 146: 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 146: selected-sense fidelity."),
    ("fidelity", "No catching, spearing, hooking, netting, cooking, roasting, stewing, eating, meat, food, taboo, storm, rain, fear, biting, illness, story, myth, or totem inference was imported.", "Rule 146: no ecology inference."),
    ("register", "Rows remained ordinary descriptions of water fauna being seen.", "Rule 146: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but fishing/cooking/taboo/story ecology should stay closed unless separately sourced.", "Rule 146: next cadence."),
    ("handoff", "Carry forward `ngiwa` exclusion, `yawu` storm/spearing trap, and `bilngkumu` story/fear trap in the next bank script.", "Rule 146: carry-forward traps."),
    ("handoff", "If a future batch opens fishing ecology, separate action verbs such as get/spear/hook/cook must be sourced and guarded independently.", "Rule 146: future ecology gate."),
]

LEXEMES = [
    ("kuyu", "noun", None, "NA", "fish", "batch-188: retained generic fish in construction consolidation."),
    ("ngawiya", "noun", None, "NA", "sea turtle", "batch-188: retained sea turtle using dictionary spelling; Patz examples also show ngawuya."),
    ("ngujay", "noun", None, "NA", "freshwater turtle", "batch-188: retained freshwater turtle only."),
    ("bilngkumu", "noun", None, "NA", "saltwater crocodile", "batch-188: retained saltwater crocodile only; fear/biting/story rows not opened."),
    ("kubarr", "noun", None, "NA", "big black freshwater eel", "batch-188: retained freshwater eel only; cooking/eating/sickness rows not opened."),
    ("yawu", "noun", None, "NA", "stingray", "batch-188: retained stingray only; storm/rain/spearing/taboo rows not opened."),
    ("yaburr", "noun", None, "NA", "shark", "batch-188: retained shark only; biting rows not opened."),
    ("kiju", "noun", None, "NA", "mud crab", "batch-188: retained mud crab only; fear/nip rows not opened."),
    ("ngalngal", "noun", None, "NA", "sand crab", "batch-188: retained sand crab; whole reduplicated lexical head."),
    ("ngiwa", "noun", None, "NA", "moray eel; sea snake; place/story-site", "batch-188: still excluded because senses are unstable for this narrow pass."),
    ("bana", "noun", None, "NA", "water", "batch-188: support-only location in bana-nga water LOC."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-188: past and present perception rows with water-fauna objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-188: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-188: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-188: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-188: 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-188-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 146 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 retained water-fauna senses and excluded ngiwa. Syntax checked past "
            "perception, water-location 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 146 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_188.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 146 targets, excluded candidate, support head, verb, participants, and pronouns.",
        artifact_path="batch_scripts/close_188.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 188: 50 accepted Rule 146 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_188.py",
        artifact_path="batch_scripts/close_188.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-188:%'").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())
