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

NOTES = (
    "LOW-COVERAGE BIRD REFERENCE LEXICAL EXPANSION AFTER RULE 210 (Rule 211). 50 rows. TARGETS: "
    "barinkan scrub bird, bilu-warra spoon bill, bujil-yiran straw-necked ibis, kalmbangarr black diver bird, "
    "dijarrdijin willie wagtail, dukunjuju golden whistler, jiwal-jiwal kingfisher, karrmbil blue mountain parakeet, "
    "kujuway brown pigeon, and yiki owl. FRAMES: TARGET yaluy, TARGET yinyay, Yinya TARGET yinyay, "
    "TARGET yinya yinyay, and Yinya TARGET yaluy. REVIEW: all target nouns stayed bare absolutive reference heads; "
    "yinya/yaluy/yinyay stayed uninflected support only; English stayed literal here/there/that reference prose. "
    "No target case, possession, comitative, instrumental, locative, derivation, number, compound, productive "
    "reduplication, flying, singing, calling, warning, message, totem, moiety, sacred/story/place, nest, egg, feather, "
    "food, hunting, catching, dance, corroboree, storm, omen, death, or support-inflection drift was opened. "
    "Initial dawadawa candidate failed lint as unhyphenated reduplication and was replaced by kalmbangarr without "
    "weakening the guard."
)

LESSONS = [
    ("process", "Rule 211 used a low-coverage bird-reference lexical field after Rule 210 water references.", "Rule 211: bird-reference cadence."),
    ("source", "Patz section 3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'.", "Rule 211: demonstrative source."),
    ("source", "Patz section 3.7 permits yinya before or after a noun; Rule 211 kept both positions but no inflected demonstrative forms.", "Rule 211: yinya position."),
    ("process", "Place-name was rejected categorically for Rule 211.", "Rule 211: field rejection."),
    ("process", "Body-part and fauna-fish were rejected because they reopen heavier possession, body-state, medical, catch, food, habitat, water, and event traps.", "Rule 211: rejected fields."),
    ("process", "Shelter-dwelling was deferred because too few clean low-coverage heads were available for a ten-head reference batch.", "Rule 211: deferred field."),
    ("process", "Dawadawa failed under-review lint as unhyphenated reduplication and was replaced by kalmbangarr rather than weakening lint.", "Rule 211: lint-preserving replacement."),
    ("lexicon", "Barinkan stayed scrub bird only; colour/body-description detail was not expanded into a property row.", "Rule 211: barinkan."),
    ("lexicon", "Bilu-warra stayed spoon bill only; no bill/body-part, feeding, water, or habitat prose was imported.", "Rule 211: bilu-warra."),
    ("lexicon", "Bujil-yiran stayed straw-necked ibis only; no neck/body-part, wetland, feeding, or movement prose was imported.", "Rule 211: bujil-yiran."),
    ("lexicon", "Kalmbangarr stayed black diver bird only; no diving, swimming, water, hunting, or habitat event was imported.", "Rule 211: kalmbangarr."),
    ("lexicon", "Dijarrdijin stayed willie wagtail only; no tail/body-part, movement, calling, or omen prose was imported.", "Rule 211: dijarrdijin."),
    ("lexicon", "Dukunjuju stayed golden whistler only; dictionary gloss typo 'golder' was corrected from the definition, and no whistling/sound event was opened.", "Rule 211: dukunjuju."),
    ("lexicon", "Jiwal-jiwal stayed kingfisher only; white-tailed detail, fishing/eating, water, and movement prose stayed closed.", "Rule 211: jiwal-jiwal."),
    ("lexicon", "Karrmbil stayed blue mountain parakeet only; no colour-property, mountain/place, flying, or call prose was imported.", "Rule 211: karrmbil."),
    ("lexicon", "Kujuway stayed brown pigeon only; brown-and-green duplicate-entry detail, flying, food, and nest prose stayed closed.", "Rule 211: kujuway."),
    ("lexicon", "Yiki stayed owl only; night-owl detail, night-event, warning, story, and sound prose stayed closed.", "Rule 211: yiki."),
    ("morphology", "All bird target nouns stayed bare: no case, possession, comitative, instrumental, locative, plural, derivation, compound, or suffixing.", "Rule 211: bare nouns."),
    ("morphology", "Lexicalized hyphenated bird names were allowed only as exact dictionary headwords; productive reduplication stayed closed.", "Rule 211: lexicalized hyphenation."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected; no demonstrative case, possessive, comitative, local-derived, or plural-human form was opened.", "Rule 211: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 211: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 211: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 211: initial demonstrative there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 211: postposed demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 211: initial demonstrative here frame."),
    ("fidelity", "English stayed literal: selected bird label plus here/there/that support only.", "Rule 211: literal English."),
    ("fidelity", "No English bird behavior, warning, totem, story, food, hunting, nest, egg, feather, storm, death, or ceremony wording was imported.", "Rule 211: denied English fields."),
    ("register", "Rows remained plain reference/location sentences, not hunting stories, omen statements, bird-behavior reports, story-place claims, or ceremonial prose.", "Rule 211: register."),
    ("handoff", "Next batch may continue from 12,747 if this closes; do not infer bird behavior, sound, totem, story, food, hunting, or morphology from Rule 211.", "Rule 211: next cadence."),
]

LEXEMES = [
    ("barinkan", "noun", None, "NA", "scrub bird", "batch-253: scrub bird noun only; colour/body-description detail not expanded."),
    ("bilu-warra", "noun", None, "NA", "spoon bill", "batch-253: spoon bill noun only; body-part/feeding/water/habitat readings closed."),
    ("bujil-yiran", "noun", None, "NA", "straw-necked ibis", "batch-253: straw-necked ibis noun only; neck/body-part/wetland/feeding/movement readings closed."),
    ("kalmbangarr", "noun", None, "NA", "black diver bird", "batch-253: black diver bird noun only; diving/swimming/water/hunting/habitat readings closed."),
    ("dijarrdijin", "noun", None, "NA", "willie wagtail", "batch-253: willie wagtail noun only; tail/body-part/movement/calling/omen readings closed."),
    ("dukunjuju", "noun", None, "NA", "golden whistler", "batch-253: golden whistler noun only; dictionary gloss typo noted; whistling/sound-event readings closed."),
    ("jiwal-jiwal", "noun", None, "NA", "kingfisher", "batch-253: kingfisher noun only; white-tailed/fishing/eating/water/movement readings closed."),
    ("karrmbil", "noun", None, "NA", "blue mountain parakeet", "batch-253: blue mountain parakeet noun only; colour/place/flying/call readings closed."),
    ("kujuway", "noun", None, "NA", "brown pigeon", "batch-253: brown pigeon noun only; brown-and-green detail/flying/food/nest readings closed."),
    ("yiki", "noun", None, "NA", "owl", "batch-253: owl noun only; night/warning/story/sound readings closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-253: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-253: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-253: distal demonstrative support only, before or after noun; no inflection."),
]


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-253-verify", note, NOW),
        )

    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail=f"After corrected rebank, 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 211 rows. Morphology checked bare bird targets and uninflected yinya/yaluy/yinyay. Lexicon checked selected bird labels only. Syntax checked five deictic/reference frames. Fidelity checked literal here/there/that English. Register stayed plain reference/location.",
        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 target case, possession, comitative, instrumental, locative, plural, derivation, compound, productive reduplication, flying, singing, calling, warning, message, totem, moiety, sacred/story/place, nest, egg, feather, food, hunting, catching, dance, corroboree, storm, omen, death, 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 211 lessons covering source checks, field rejection, corrected rebank, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_253.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 211 targets and demonstrative heads.",
        artifact_path="batch_scripts/close_253.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 253: 50 accepted Rule 211 low-coverage bird reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_253.py",
        artifact_path="batch_scripts/close_253.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())
