#!/usr/bin/env python3
"""Close batch-257 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-257"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-257-second-low-frequency-person-quality-adjective-expansion-after-rule214-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "SECOND LOW-FREQUENCY PERSON-QUALITY ADJECTIVE EXPANSION AFTER RULE 214 (Rule 215). 50 rows. TARGETS: "
    "bangkarr-wumba humble, dukul-dandi stubborn, jakay-dandi stingy, janbay-janbay cheeky, jayarr-jayarr pleasant, "
    "juburr experienced, kulun selfish, mara-jalajala clumsy, mini-mini beautiful, and mumbar careful. SUPPORT: "
    "bama person/people plus uninflected yinya/yaluy/yinyay. FRAMES: Bama TARGET, Bama TARGET yaluy, Bama TARGET "
    "yinyay, Yinya bama TARGET, and Yinya bama TARGET yinyay. REVIEW: target adjectives stayed bare property words. "
    "No target case, degree, comparison, negation, privative -kari, inchoative, causative, derivation, compound "
    "productivity, productive reduplication, body/hand/neck etymology expansion, speech/talk complement, activity "
    "complement, food/giving, legal/social-event, animal-tameness, work/complement, support inflection, or Rule 214 "
    "person-quality drift was opened."
)

LESSONS = [
    ("process", "Rule 215 continued the low-frequency person-quality adjective field only because the same sourced bama property frames remained safe.", "Rule 215: second person-quality cadence."),
    ("source", "Patz section 3.1 treats adjectives as nominals denoting properties of nominal referents, including value and mental characteristics.", "Rule 215: adjective source."),
    ("source", "Patz section 3.1 gives bama as a generic noun/classifier for Aboriginal person/people; Rule 215 uses bama only as a person support noun.", "Rule 215: bama support."),
    ("source", "Patz section 3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'; Rule 215 keeps all three uninflected.", "Rule 215: demonstrative source."),
    ("process", "Food-reference was rejected for this pass because low-frequency entries carried cooking, leaching, loan, medicine, alcohol, and post-contact tails.", "Rule 215: rejected food field."),
    ("process", "Minday, muna, ngarrku-ngarrku, and malaji were held out because they pull animal-tameness, work/complement, or legal/social-event pressure.", "Rule 215: held candidates."),
    ("lexicon", "Bangkarr-wumba stayed humble person-quality only; body-compound etymology did not open body-part rows.", "Rule 215: bangkarr-wumba."),
    ("lexicon", "Dukul-dandi stayed stubborn person-quality only; no argument, disobedience, or social-event row was opened.", "Rule 215: dukul-dandi."),
    ("lexicon", "Jakay-dandi stayed stingy person-quality only; neck-compound etymology and giving/food contexts stayed closed.", "Rule 215: jakay-dandi."),
    ("lexicon", "Janbay-janbay stayed cheeky person-quality only; the pronoun usage did not open second-person or plural frames.", "Rule 215: janbay-janbay."),
    ("lexicon", "Jayarr-jayarr stayed pleasant person-quality only; 'nice to talk to' did not open speech or talking complements.", "Rule 215: jayarr-jayarr."),
    ("lexicon", "Juburr stayed experienced person-quality only; expert/clever-at-something wording did not open an activity complement.", "Rule 215: juburr."),
    ("lexicon", "Kulun stayed selfish person-quality only; food/giving usage stayed closed.", "Rule 215: kulun."),
    ("lexicon", "Mara-jalajala stayed clumsy person-quality only; hand-compound etymology did not open hand/body-part rows.", "Rule 215: mara-jalajala."),
    ("lexicon", "Mini-mini stayed beautiful person-quality only; mini/correct derivation and niceness expansion stayed closed.", "Rule 215: mini-mini."),
    ("lexicon", "Mumbar stayed careful person-quality only; proper/correct/alert alternatives and crocodile alert usage stayed closed.", "Rule 215: mumbar."),
    ("morphology", "All target adjectives stayed bare: no target case, degree, comparison, negation, privative, inchoative, causative, plural, derivation, or suffixing.", "Rule 215: bare adjectives."),
    ("morphology", "Lexicalized hyphenated and reduplicated dictionary headwords were admitted only as whole heads; no productive reduplication or new compounding was opened.", "Rule 215: lexicalized reduplication guard."),
    ("morphology", "Bama, yinya, yaluy, and yinyay stayed uninflected support forms only.", "Rule 215: support morphology."),
    ("syntax", "Rows 1-10 used Bama TARGET.", "Rule 215: NP ADJ frame."),
    ("syntax", "Rows 11-20 used Bama TARGET yaluy.", "Rule 215: NP ADJ here frame."),
    ("syntax", "Rows 21-30 used Bama TARGET yinyay.", "Rule 215: NP ADJ there frame."),
    ("syntax", "Rows 31-40 used Yinya bama TARGET.", "Rule 215: demonstrative NP ADJ frame."),
    ("syntax", "Rows 41-50 used Yinya bama TARGET yinyay.", "Rule 215: demonstrative NP ADJ there frame."),
    ("fidelity", "English stayed literal: person plus selected adjective plus optional here/there/that support.", "Rule 215: literal English."),
    ("fidelity", "No English degree, negation, work, food, giving, asking, talking, hunting, fighting, stealing, legal, animal, body-part, or event wording was imported.", "Rule 215: denied English fields."),
    ("register", "Rows remained plain elicitation-style property statements, not moral judgments, narratives, commands, work reports, legal claims, or social-event descriptions.", "Rule 215: register."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, and live docs are required evidence before treating Rule 215 as complete.", "Rule 215: evidence standard."),
    ("handoff", "Next batch may continue from 12,947 if this closes; do not infer social events, degree, negation, action complements, body etymology, or morphology from Rule 215.", "Rule 215: next cadence."),
]

LEXEMES = [
    ("bama", "noun", None, "NA", "person; people", "batch-257: support noun only, person/people reading; no kin/social-event expansion."),
    ("bangkarr-wumba", "adjective", None, "NA", "humble", "batch-257: humble person-quality only; bangkarr/body etymology closed."),
    ("dukul-dandi", "adjective", None, "NA", "stubborn", "batch-257: stubborn person-quality only; argument/disobedience event readings closed."),
    ("jakay-dandi", "adjective", None, "NA", "stingy", "batch-257: stingy person-quality only; jakay/neck etymology and giving/food contexts closed."),
    ("janbay-janbay", "adjective", None, "NA", "cheeky", "batch-257: cheeky person-quality only; pronoun/plural usage closed."),
    ("jayarr-jayarr", "adjective", None, "NA", "pleasant", "batch-257: pleasant person-quality only; speech/talking complement closed."),
    ("juburr", "adjective", None, "NA", "experienced", "batch-257: experienced person-quality only; expert-at/activity complement closed."),
    ("kulun", "adjective", None, "NA", "selfish", "batch-257: selfish person-quality only; food/giving usage closed."),
    ("mara-jalajala", "adjective", None, "NA", "clumsy", "batch-257: clumsy person-quality only; mara/hand etymology closed."),
    ("mini-mini", "adjective", None, "NA", "beautiful", "batch-257: beautiful person-quality only; mini/correct derivation closed."),
    ("mumbar", "adjective", None, "NA", "careful", "batch-257: careful person-quality only; proper/correct/alert alternatives and crocodile usage closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-257: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-257: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-257: distal demonstrative support only; 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-257-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 215 rows. Morphology checked bare whole-head adjectives and uninflected bama/yinya/yaluy/yinyay support. Lexicon checked selected adjective senses only. Syntax checked five nominal-adjective frames. Fidelity checked literal person-quality English. Register stayed plain property 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 target case, degree, comparison, negation, privative -kari, inchoative, causative, derivation, productive compounding, productive reduplication, body/hand/neck etymology expansion, speech/talk complement, activity complement, food/giving, legal/social-event, animal-tameness, work/complement, support inflection, or Rule 214 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 215 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_257.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 215 targets and support heads.",
        artifact_path="batch_scripts/close_257.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 257: 50 accepted Rule 215 second low-frequency person-quality adjective rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_257.py",
        artifact_path="batch_scripts/close_257.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 or 0}->{words_after or 0}"
    )
    return 0


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