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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 143 (Rule 144). 50 rows. TARGETS RETAINED: dikal generic bird, kurranji "
    "cassowary, diwan scrub turkey, wabul Torres Strait Island pigeon, nili-nili duck, kalbu black crow, dulku white "
    "crane, birrbirr parrot/lorikeet, jamarbina goose. FRAMES: standing, past perception, present perception. REVIEW: "
    "no new target heads, no eggs/nests, no hunting/food/meat/eating, no omen/messenger/totem/storm-warning/myth/story "
    "claims, no target case forms, no instruments, no comitatives, no possessives, no compounds; wakuka and jarruka "
    "still excluded; common-noun A ERG, pronoun A bare."
)

LESSONS = [
    ("process", "A construction pass after a bird-name lexical expansion should reuse the bird heads in safe frames before opening any bird ecology.", "Rule 144: construction before ecology."),
    ("process", "Present `nyajil` can consolidate perception only when the English is present tense and the analysis keeps `nyaji-l` explicit.", "Rule 144: present perception."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 144: duplicate preflight."),
    ("lexicon", "`dikal` remained generic bird.", "Rule 144: dikal retained."),
    ("lexicon", "`kurranji` remained cassowary only.", "Rule 144: kurranji retained."),
    ("lexicon", "`diwan` remained scrub turkey only; domestic turkey and egg rows stayed closed.", "Rule 144: diwan retained."),
    ("lexicon", "`wabul` remained Torres Strait Island pigeon only, not a human/islander reading.", "Rule 144: wabul retained."),
    ("lexicon", "`nili-nili` remained a whole duck head.", "Rule 144: nili-nili retained."),
    ("lexicon", "`kalbu` remained black crow/species of crow only; totem claims stayed closed.", "Rule 144: kalbu retained."),
    ("lexicon", "`dulku` remained white crane only.", "Rule 144: dulku retained."),
    ("lexicon", "`birrbirr` remained a whole parrot/lorikeet head.", "Rule 144: birrbirr retained."),
    ("lexicon", "`jamarbina` remained goose only.", "Rule 144: jamarbina retained."),
    ("lexicon", "`wakuka` and `jarruka` remained excluded.", "Rule 144: excluded bird traps."),
    ("morphology", "All bird target heads stayed bare; no target dative, locative, ablative, instrumental, comitative, possessive, or compound forms appeared.", "Rule 144: target case restraint."),
    ("morphology", "The only support local forms were `bayan-ba`, `madja-nga`, and `ngalkal-ba`; `yinyay` stayed deictic support.", "Rule 144: support form limit."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 144: A marking."),
    ("syntax", "Standing rows used `janay` with one support location.", "Rule 144: standing syntax."),
    ("syntax", "Past perception rows used `nyajin` with bare bird objects and optional support location.", "Rule 144: past perception syntax."),
    ("syntax", "Present perception rows used `nyajil` with bare bird objects.", "Rule 144: present perception syntax."),
    ("fidelity", "English labels explicitly named selected bird senses, especially scrub turkey and Torres Strait Island pigeon.", "Rule 144: selected-sense fidelity."),
    ("fidelity", "No row translated `wabul` as a human/islander or `diwan` as domestic turkey.", "Rule 144: polysemy control."),
    ("fidelity", "No egg, nest, hunting, food, meat, eating, omen, messenger, totem, storm-warning, mythic, or story inference was imported.", "Rule 144: no bird-use inference."),
    ("register", "Rows remained ordinary descriptions of birds standing somewhere or being seen.", "Rule 144: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but bird-use ecology should stay closed unless separately sourced.", "Rule 144: next cadence."),
    ("handoff", "Carry forward the `wabul` translation-tag trap and the `wakuka`/`jarruka` exclusion in the next bank script.", "Rule 144: carry-forward traps."),
]

LEXEMES = [
    ("dikal", "noun", None, "NA", "bird", "batch-186: retained generic bird in construction consolidation."),
    ("kurranji", "noun", None, "NA", "cassowary", "batch-186: retained cassowary only."),
    ("diwan", "noun", None, "NA", "scrub turkey", "batch-186: retained scrub turkey only; domestic turkey and eggs not opened."),
    ("wabul", "noun", None, "NA", "Torres Strait Island pigeon", "batch-186: retained pigeon bird sense only."),
    ("nili-nili", "noun", None, "NA", "duck", "batch-186: retained duck; whole reduplicated lexical head."),
    ("kalbu", "noun", None, "NA", "black crow", "batch-186: retained black crow / species of crow only; totem claims not opened."),
    ("dulku", "noun", None, "NA", "white crane", "batch-186: retained white crane only."),
    ("birrbirr", "noun", None, "NA", "parrot; lorikeet", "batch-186: retained parrot/lorikeet; whole lexical head."),
    ("jamarbina", "noun", None, "NA", "goose", "batch-186: retained goose only."),
    ("wakuka", "noun", None, "NA", "crow; kookaburra", "batch-186: still excluded because dictionary/corpus sense selection is unstable."),
    ("jarruka", "noun", None, "NA", "scrub hen; scrub-hen eggs/nest", "batch-186: still excluded because egg/nest polysemy was out of scope."),
    ("bayan", "noun", None, "NA", "camp; house", "batch-186: support-only location in bayan-ba camp LOC."),
    ("madja", "noun", None, "NA", "scrub", "batch-186: support-only location in madja-nga scrub LOC."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-186: support-only outside location in ngalkal-ba."),
    ("yinyay", "locational", None, "NA", "there", "batch-186: deictic support in perception rows."),
    ("jana-y", "intransitive-verb", "y", "NA", "stand; be", "batch-186: standing rows with bird names."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-186: past and present perception rows with bird objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-186: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-186: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-186: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-186: 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-186-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 144 rows. Morphology checked bare bird targets, no target case "
            "morphology, no instruments/comitatives/possessives, support-only local forms, common-noun A ERG, and "
            "pronoun A bare. Lexicon checked retained bird senses and excluded wakuka/jarruka. Syntax checked standing, "
            "past perception, and present perception frames. Fidelity checked bird-sense English. 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 egg/nest row, no hunting/food/meat/eating row, no omen/messenger/totem/"
            "storm-warning/myth/story claim, no target instrument row, no target case form, no unresolved wakuka or "
            "jarruka row, and no carry-forward bajar/mili/ngalku/tree-use 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 144 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_186.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 144 targets, excluded candidates, support/deictic heads, verbs, participants, and pronouns.",
        artifact_path="batch_scripts/close_186.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 186: 50 accepted Rule 144 construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_186.py",
        artifact_path="batch_scripts/close_186.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-186:%'").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())
