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

NOTES = (
    "THIRD KIN-REFERENCE LEXICAL EXPANSION AFTER RULE 227 (Rule 228). 50 rows. TARGETS: "
    "jinkurr younger sister, mukay mother's older sister, biwar wife, kuban wife, manyarr wife, "
    "ngalayin father-in-law, banji brother-in-law, warrin sister-in-law, bangunji cousin, and kambanmu cross-cousin. "
    "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 kin-reference labels. "
    "No Rule 157/159 exact-target repeat, kinship possession, kinship plural -karra, dyadic -manda, address form, "
    "comparison, marriage/change-of-state row, avoidance behavior, name-taboo practice, moiety row, speaker-sex "
    "niece/nephew row, couple/spouse-register row, target case, productive compounding, productive reduplication, "
    "or support inflection was opened."
)

LESSONS = [
    ("process", "Rule 228 selected third kin-reference targets only after checking Rules 157-160, dictionary entries, exact surfaces, and recent Rule 227 carry-forward traps.", "Rule 228: third kin-reference cadence."),
    ("source", "Patz section 3.1 explicitly includes human beings and kinship terms among nouns, supporting bare kin-reference nouns.", "Rule 228: kin noun source."),
    ("source", "Patz section 3.7 and existing corpus law support yinya, yaluy, and yinyay as uninflected demonstrative/local support.", "Rule 228: deictic support."),
    ("source", "Rules 157-160 already source human/kin reference in bare deictic identification and deictic-supported frames; Rule 228 reuses only the deictic subset.", "Rule 228: construction source."),
    ("process", "Rejected or deferred candidates included Rule 157 and Rule 159 exact targets, biwul, ngalba, manda, ngujurr, mandi, kubananji, manyarrinyu, ngaybirr, and mukul.", "Rule 228: candidate filtering."),
    ("lexicon", "Jinkurr stayed younger-sister reference only; no sibling plural, address, or family-event row was opened.", "Rule 228: jinkurr."),
    ("lexicon", "Mukay stayed mother's-older-sister reference only; the father's-older-brother reading stayed closed in this batch.", "Rule 228: mukay."),
    ("lexicon", "Biwar stayed wife reference only; no marriage event, possession, or husband-wife contrast row was opened.", "Rule 228: biwar."),
    ("lexicon", "Kuban stayed wife reference only; the related married-man noun kubananji stayed closed.", "Rule 228: kuban."),
    ("lexicon", "Manyarr stayed wife reference only; the couple noun manyarrinyu stayed closed.", "Rule 228: manyarr."),
    ("lexicon", "Ngalayin stayed father-in-law reference only; son-in-law reciprocity and avoidance behavior stayed closed.", "Rule 228: ngalayin."),
    ("lexicon", "Banji stayed brother-in-law reference only; sister-in-law alternation and actual-relationship prose did not become event content.", "Rule 228: banji."),
    ("lexicon", "Warrin stayed sister-in-law reference only; brother-in-law alternation and actual-relationship prose did not become event content.", "Rule 228: warrin."),
    ("lexicon", "Bangunji stayed cousin reference only; full-blood kin prose did not open social or possession frames.", "Rule 228: bangunji."),
    ("lexicon", "Kambanmu stayed cross-cousin reference only; mother's-brother/father's-sister source prose did not open possessive or descent explanations in rows.", "Rule 228: kambanmu."),
    ("morphology", "All target kin nouns stayed bare: no target case, possession, comitative, instrumental, locative, plural, kin plural, dyadic, derivational, or suffixal morphology.", "Rule 228: bare kin targets."),
    ("morphology", "Kin plural -karra and dyadic -manda remain closed; no new plural or kin-pair morphology was inferred from the target field.", "Rule 228: no kin plural/dyad."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads.", "Rule 228: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 228: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 228: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 228: preposed demonstrative frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 228: postposed demonstrative frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 228: that-here frame."),
    ("fidelity", "English stayed literal reference prose: selected kin label plus here/there/that.", "Rule 228: literal English."),
    ("fidelity", "The batch did not turn dictionary relationship definitions into possession, marriage, avoidance, moiety, address, social conduct, or family-narrative claims.", "Rule 228: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements, not marriage commentary, avoidance instruction, family story, social law, or ceremonial prose.", "Rule 228: register."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, and live docs are required before treating Rule 228 as complete.", "Rule 228: evidence standard."),
    ("handoff", "Next batch may continue from 13,597 if this closes; do not infer possession, plural, dyadic, avoidance, marriage, moiety, address, or kin-event grammar from Rule 228.", "Rule 228: next cadence."),
]

LEXEMES = [
    ("jinkurr", "noun", None, "NA", "younger sister", "batch-270: younger-sister reference only."),
    ("mukay", "noun", None, "NA", "mother's older sister", "batch-270: mother's-older-sister reference only; father's-older-brother reading closed here."),
    ("biwar", "noun", None, "NA", "wife", "batch-270: wife reference only; no marriage-event row."),
    ("kuban", "noun", None, "NA", "wife", "batch-270: wife reference only; kubananji married-man noun closed."),
    ("manyarr", "noun", None, "NA", "wife", "batch-270: wife reference only; manyarrinyu couple noun closed."),
    ("ngalayin", "noun", None, "NA", "father-in-law", "batch-270: father-in-law reference only; son-in-law reciprocity and avoidance behavior closed."),
    ("banji", "noun", None, "NA", "brother-in-law", "batch-270: brother-in-law reference only; sister-in-law alternation closed here."),
    ("warrin", "noun", None, "NA", "sister-in-law", "batch-270: sister-in-law reference only; brother-in-law alternation closed here."),
    ("bangunji", "noun", None, "NA", "cousin", "batch-270: cousin reference only."),
    ("kambanmu", "noun", None, "NA", "cross-cousin", "batch-270: cross-cousin reference only; source-prose kin explanation not expanded."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-270: demonstrative support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-270: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-270: 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-270-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 228 rows. Morphology checked bare kin nouns and uninflected support. Lexicon checked selected kin-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 157/159 exact-target repeat, kinship possession, kinship plural -karra, dyadic -manda, address form, comparison, marriage/change-of-state row, avoidance behavior, name-taboo practice, moiety row, speaker-sex niece/nephew row, couple/spouse-register row, 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 228 lessons covering source checks, candidate rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_270.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 228 targets and support heads.",
        artifact_path="batch_scripts/close_270.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 270: 50 accepted Rule 228 third kin-reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_270.py",
        artifact_path="batch_scripts/close_270.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())
