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

NOTES = (
    "SECOND INSECT-REFERENCE LEXICAL EXPANSION AFTER RULE 221 (Rule 222). 50 rows. TARGETS: "
    "kira-kira black ant, kandal maggot, kinga caterpillar, mulma hornet, biringal scorpion, birinjil centipede, "
    "kurrmbal cicada, nganjamu worm, kurran grub, and ngirran beetle. 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 insect-reference labels. No Rule 212 exact target duplicate, food/egg/"
    "honey/medicine-heavy row, bite/sting/sickness/nest row, homograph/material/story/body row, unhyphenated-"
    "reduplication pressure, seasonal/event-signal row, target case, number morphology, derivation, productive "
    "compounding, productive reduplication, support inflection, bird-reference drift, reptile/amphibian-reference "
    "drift, mammal-reference drift, or fish-reference drift was opened."
)

LESSONS = [
    ("process", "Rule 222 continued lexical coverage only after checking earlier Rule 212 insect targets for exact surface collisions.", "Rule 222: second insect lexical cadence."),
    ("source", "Patz section 3.1 says nouns include fauna; Rule 222 uses bare insect-reference nouns only.", "Rule 222: insect noun source."),
    ("source", "Patz section 3.7 supports yinya, yaluy, and yinyay; Rule 222 keeps all three uninflected.", "Rule 222: demonstrative source."),
    ("process", "Rule 222 reused bare deictic reference frames because they add lexical coverage without importing insect behavior, use, food, medicine, habitat, or event grammar.", "Rule 222: reference wording."),
    ("process", "Rejected or deferred fields included prior Rule 212 targets, food/egg/honey/medicine-heavy entries, bite/sting/sickness/nest-heavy entries, homographs, unhyphenated reduplication pressure, and event-signal entries.", "Rule 222: rejected insect fields."),
    ("lexicon", "Kira-kira stayed black-ant reference only; productive reduplication and kira baby-girl homophone stayed closed.", "Rule 222: kira-kira."),
    ("lexicon", "Kandal stayed maggot reference only; fly-larva explanation, decay, food, body, and event prose stayed closed.", "Rule 222: kandal."),
    ("lexicon", "Kinga stayed caterpillar reference only; eating, medicine, and habitat prose stayed closed.", "Rule 222: kinga."),
    ("lexicon", "Mulma stayed hornet reference only; sting, nest, and danger prose stayed closed.", "Rule 222: mulma."),
    ("lexicon", "Biringal stayed scorpion reference only; Patz example evidence did not open bite, danger, or event prose.", "Rule 222: biringal."),
    ("lexicon", "Birinjil stayed centipede reference only; biting and danger prose stayed closed.", "Rule 222: birinjil."),
    ("lexicon", "Kurrmbal stayed cicada reference only; locust variant, sound, season, and event prose stayed closed.", "Rule 222: kurrmbal."),
    ("lexicon", "Nganjamu stayed worm reference only; soil, food, and fishing-bait prose stayed closed.", "Rule 222: nganjamu."),
    ("lexicon", "Kurran stayed grub reference only; edible, wood, habitat, and use prose stayed closed.", "Rule 222: kurran."),
    ("lexicon", "Ngirran stayed beetle reference only; adult-from-mujurr note stayed lexical and no life-cycle or food prose was opened.", "Rule 222: ngirran."),
    ("morphology", "All target insect nouns stayed bare: no target case, possession, comitative, instrumental, locative, number, derivation, suffixing, plural, or reduplication.", "Rule 222: bare nouns."),
    ("morphology", "English modifiers inside labels, such as black in black ant, remained lexical labels rather than Kuku morphology or separate predicates.", "Rule 222: label morphology guard."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support forms only.", "Rule 222: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 222: TARGET here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 222: TARGET there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 222: demonstrative TARGET there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 222: TARGET demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 222: demonstrative TARGET here frame."),
    ("fidelity", "English stayed literal reference prose: target insect label plus here/there/that support.", "Rule 222: literal English."),
    ("fidelity", "The batch did not turn source definitions into bite, sting, sickness, honey, medicine, food, habitat, season, or story claims.", "Rule 222: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style reference statements, not warnings, food statements, medicine statements, ecological descriptions, or collection/use reports.", "Rule 222: 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 222 as complete.", "Rule 222: evidence standard."),
    ("handoff", "Next batch may continue from 13,297 if this closes; do not infer insect behavior, use, food, medicine, habitat, homograph, or event grammar from Rule 222.", "Rule 222: next cadence."),
]

LEXEMES = [
    ("kira-kira", "noun", None, "NA", "black ant", "batch-264: black-ant reference only; productive reduplication and kira baby-girl homophone closed."),
    ("kandal", "noun", None, "NA", "maggot", "batch-264: maggot reference only; fly-larva explanation/decay/food/body/event prose closed."),
    ("kinga", "noun", None, "NA", "caterpillar", "batch-264: caterpillar reference only; eating/medicine/habitat prose closed."),
    ("mulma", "noun", None, "NA", "hornet", "batch-264: hornet reference only; sting/nest/danger prose closed."),
    ("biringal", "noun", None, "NA", "scorpion", "batch-264: scorpion reference only; Patz example evidence did not open bite/danger/event prose."),
    ("birinjil", "noun", None, "NA", "centipede", "batch-264: centipede reference only; biting/danger prose closed."),
    ("kurrmbal", "noun", None, "NA", "cicada", "batch-264: cicada reference only; locust variant/sound/season/event prose closed."),
    ("nganjamu", "noun", None, "NA", "worm", "batch-264: worm reference only; soil/food/fishing-bait prose closed."),
    ("kurran", "noun", None, "NA", "grub", "batch-264: grub reference only; edible/wood/habitat/use prose closed."),
    ("ngirran", "noun", None, "NA", "beetle", "batch-264: beetle reference only; adult-from-mujurr note stayed lexical, no life-cycle/food prose."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-264: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-264: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-264: 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-264-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 222 rows. Morphology checked bare insect nouns and uninflected yinya/yaluy/yinyay support. Lexicon checked selected insect-reference labels only. Syntax checked five deictic reference frames. 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 212 exact target duplicate, food/egg/honey/medicine-heavy row, bite/sting/sickness/nest row, homograph/material/story/body row, unhyphenated-reduplication pressure, seasonal/event-signal row, target case, number morphology, derivation, productive compounding, productive reduplication, support inflection, bird-reference drift, reptile/amphibian-reference drift, mammal-reference drift, or fish-reference 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 222 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_264.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 222 targets and support heads.",
        artifact_path="batch_scripts/close_264.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 264: 50 accepted Rule 222 second insect-reference rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_264.py",
        artifact_path="batch_scripts/close_264.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())
