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

NOTES = (
    "THIRD BIRD-REFERENCE LEXICAL EXPANSION AFTER RULE 228 (Rule 229). 50 rows. TARGETS: "
    "baringkan baringkan small bird, bidu-bidu bank bird, diwalngku migratory bird, jiral-jiral night bird, "
    "karkunbay stockwhip bird, dukunjulu golden whistler, kurranday seagull, yinjul fig parrot, "
    "milman azure kingfisher, and nili-nili duck. SUPPORT: uninflected yinya/yaluy/yinyay. FRAMES: "
    "TARGET yaluy, TARGET yinyay, Yinya TARGET yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. "
    "REVIEW: all target nouns stayed bare bird-reference labels. No Rule 173/211/221 exact-target repeat, "
    "unhyphenated reduplication variant, flight/call/song/migration event, warning/message/death/omen row, "
    "totem/moiety/sacred/story/country row, nest/egg/feather/wing/food/hunting/catching row, habitat/water/tree "
    "row, colour predicate, loan/domestic-bird import, target case, productive compounding, productive reduplication, "
    "or support inflection was opened."
)

LESSONS = [
    ("process", "Rule 229 selected a third bird-reference field only after checking Rules 173, 211, and 221, dictionary entries, exact planned surfaces, and cultural-prose traps.", "Rule 229: bird-reference cadence."),
    ("source", "Patz section 3.1 explicitly includes fauna among nouns, supporting bare bird-reference nouns.", "Rule 229: fauna noun source."),
    ("source", "Patz section 3.7 and existing corpus law support yinya, yaluy, and yinyay as uninflected demonstrative/local support.", "Rule 229: deictic support."),
    ("source", "Rules 211 and 221 already source bird-reference nouns in bare deictic frames; Rule 229 reuses only that narrow construction law.", "Rule 229: construction source."),
    ("process", "Rejected or deferred candidates included Rule 173/211/221 exact targets, unhyphenated reduplication variants, messenger/storm/death/totem/story birds, loan/domestic birds, and homograph-heavy kulbal/wandi/waja.", "Rule 229: candidate filtering."),
    ("lexicon", "Baringkan stayed baringkan-small-bird reference only; no size adjective or generic small-bird taxonomy was inferred.", "Rule 229: baringkan."),
    ("lexicon", "Bidu-bidu stayed bank-bird reference only; the hyphenated reduplicated bird name was treated as one lexical head.", "Rule 229: bidu-bidu."),
    ("lexicon", "Diwalngku stayed migratory-bird reference only; no migration, flying, route, season, or motion event was opened.", "Rule 229: diwalngku."),
    ("lexicon", "Jiral-jiral stayed night-bird reference only; no night-time event, calling, omen, or behaviour row was opened.", "Rule 229: jiral-jiral."),
    ("lexicon", "Karkunbay stayed stockwhip-bird reference only; no whip artefact, sound, call, or warning reading was opened.", "Rule 229: karkunbay."),
    ("lexicon", "Dukunjulu stayed golden-whistler reference only; no whistling, singing, sound, or colour-predicate row was opened.", "Rule 229: dukunjulu."),
    ("lexicon", "Kurranday stayed seagull reference only; dirrmbay storm-warning/death-message senses stayed closed.", "Rule 229: kurranday."),
    ("lexicon", "Yinjul stayed fig-parrot reference only; no fig-tree, feeding, colour, or habitat row was opened.", "Rule 229: yinjul."),
    ("lexicon", "Milman stayed azure-kingfisher reference only; no colour predicate, fishing, water, or diving event was opened.", "Rule 229: milman."),
    ("lexicon", "Nili-nili stayed duck reference only; the hyphenated reduplicated bird name was treated as one lexical head.", "Rule 229: nili-nili."),
    ("morphology", "All target bird nouns stayed bare: no target case, possession, comitative, instrumental, locative, plural, derivational, or suffixal morphology.", "Rule 229: bare bird targets."),
    ("morphology", "Hyphenated lexical reduplications bidu-bidu, jiral-jiral, and nili-nili stayed whole dictionary headwords, not productive plural or generated reduplication.", "Rule 229: lexical reduplication."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads.", "Rule 229: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 229: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 229: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 229: preposed demonstrative frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 229: postposed demonstrative frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 229: that-here frame."),
    ("fidelity", "English stayed literal reference prose: selected bird label plus here/there/that.", "Rule 229: literal English."),
    ("fidelity", "The batch did not turn dictionary bird prose into flight, call, warning, message, totem, death, story, food, habitat, water, tree, colour, or use claims.", "Rule 229: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements, not bird lore, ecological description, warning practice, hunting talk, food prose, or ceremonial narrative.", "Rule 229: register."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, and live docs are required before treating Rule 229 as complete.", "Rule 229: evidence standard."),
    ("handoff", "Next batch may continue from 13,647 if this closes; do not infer bird behavior, omen, totem, habitat, food, colour, or use grammar from Rule 229.", "Rule 229: next cadence."),
]

LEXEMES = [
    ("baringkan", "noun", None, "NA", "baringkan small bird", "batch-271: baringkan small-bird reference only."),
    ("bidu-bidu", "noun", None, "NA", "bank bird", "batch-271: bank-bird reference only; whole hyphenated lexical head."),
    ("diwalngku", "noun", None, "NA", "diwalngku migratory bird", "batch-271: migratory-bird reference only; no migration event."),
    ("jiral-jiral", "noun", None, "NA", "night bird", "batch-271: night-bird reference only; whole hyphenated lexical head."),
    ("karkunbay", "noun", None, "NA", "stockwhip bird", "batch-271: stockwhip-bird reference only; no sound/whip event."),
    ("dukunjulu", "noun", None, "NA", "golden whistler", "batch-271: golden-whistler reference only; no whistling or colour predicate."),
    ("kurranday", "noun", None, "NA", "seagull", "batch-271: seagull reference only; storm-warning/death-message senses closed."),
    ("yinjul", "noun", None, "NA", "fig parrot", "batch-271: fig-parrot reference only; no fig-tree or feeding row."),
    ("milman", "noun", None, "NA", "azure kingfisher", "batch-271: azure-kingfisher reference only; no colour/fishing/water row."),
    ("nili-nili", "noun", None, "NA", "duck", "batch-271: duck reference only; whole hyphenated lexical head."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-271: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-271: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-271: local demonstrative support only."),
]


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-271-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 229 rows. Morphology checked bare bird nouns, lexicalized hyphenated reduplications, and uninflected support. Lexicon checked selected bird-reference labels only. Syntax checked five deictic frame bands. Fidelity checked literal reference English. Register stayed plain reference statement.",
        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 Rule 173/211/221 exact-target repeat, unhyphenated reduplication variant, flight/call/song/migration event, warning/message/death/omen row, totem/moiety/sacred/story/country row, nest/egg/feather/wing/food/hunting/catching row, habitat/water/tree row, colour predicate, loan/domestic-bird import, target case, productive compound, productive reduplication, or support inflection.",
        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 229 lessons covering source checks, candidate rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_271.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 229 targets and support heads.",
        artifact_path="batch_scripts/close_271.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 271: 50 accepted Rule 229 third bird-reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_271.py",
        artifact_path="batch_scripts/close_271.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_after, words_after = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    print(
        f"closed {LABEL}: accepted=50, reviews={reviews}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before}->{words_after}"
    )
    return 0


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