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

NOTES = (
    "REPTILE REFERENCE LEXICAL EXPANSION AFTER RULE 174 (Rule 175). 50 rows. TARGETS: banamu fresh water snake, "
    "binju light bellied black snake, dukul-mukul dukul-mukul lizard, jirabay ground lizard, junbirr small lizard, "
    "kabuljaka striped water snake, kulmba-kulmba gecko, kurriyala carpet snake, ngawurr-ngawun freshwater crocodile, "
    "and ngumbul sea snake. FRAMES: bare yaluy deictic identification, bare present perception with ngayu, "
    "yinyay-supported present perception with yundu, yinyay-supported past perception with jana, and yaluy-supported "
    "present perception with ngana. REVIEW: all targets stayed bare; rejected reptile candidates and older reptile rows "
    "did not license wrong-marriage, cooking, poisonous, fish/grunter, belt/source, running-from, story, story-site, "
    "legend, mythological-person, food, edible, eating, hunting, catching, chase, firestick, eye/fighter, place, river, "
    "egg, body-part, target case, target compound, possession, or event semantics."
)

LESSONS = [
    ("process", "A lexical pass after Rule 174 selected unused reptile reference nouns with exact dictionary readback.", "Rule 175: lexical cadence after Rule 174."),
    ("process", "Rule 175 selected ten zero-hit reptile heads rather than recycling older reptile rows with story, food, poison, or place predicates.", "Rule 175: unused target discipline."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 175: duplicate preflight."),
    ("process", "`kurriyala` was admitted only as carpet snake; its fish/grunter homograph and Patz story/source/avoidance examples remain closed.", "Rule 175: kurriyala sense discipline."),
    ("process", "`binju` was admitted only as light bellied black snake; wrong-marriage, cooking, and poisonous senses remain closed.", "Rule 175: binju sense discipline."),
    ("lexicon", "`banamu` is fresh water snake only; no water-route, bite, poison, food, or event row.", "Rule 175: banamu."),
    ("lexicon", "`binju` is light bellied black snake only; no wrong-marriage, cooking, or poison row.", "Rule 175: binju."),
    ("lexicon", "`dukul-mukul` is dukul-mukul lizard only; no body-part head or size-comparison row.", "Rule 175: dukul-mukul."),
    ("lexicon", "`jirabay` is ground lizard only; no blue-tongue comparison, ground-place, or movement row.", "Rule 175: jirabay."),
    ("lexicon", "`junbirr` is small lizard only; no wet-season, grass, marking, or body-part row.", "Rule 175: junbirr."),
    ("lexicon", "`kabuljaka` is striped water snake only; no zebra comparison, water-route, bite, or poison row.", "Rule 175: kabuljaka."),
    ("lexicon", "`kulmba-kulmba` is gecko only; no house-place, smallness predicate, or movement row.", "Rule 175: kulmba-kulmba."),
    ("lexicon", "`kurriyala` is carpet snake only; no fish/grunter, story, source-material, belt, or running-from row.", "Rule 175: kurriyala."),
    ("lexicon", "`ngawurr-ngawun` is freshwater crocodile only; no saltwater contrast, attack, hunting, or story row.", "Rule 175: ngawurr-ngawun."),
    ("lexicon", "`ngumbul` is sea snake only; no sea-place, bite, poison, or event row.", "Rule 175: ngumbul."),
    ("morphology", "All target heads stayed bare; no target LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, reduplicated, or compound morphology was produced.", "Rule 175: target case restraint."),
    ("morphology", "Reduplicated lexical heads `dukul-mukul`, `kulmba-kulmba`, and `ngawurr-ngawun` were treated as whole dictionary heads.", "Rule 175: reduplicated lexical heads."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 175: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 175: perception tense forms."),
    ("syntax", "Rows 1-10 used one reptile target plus `yaluy` with no predicator.", "Rule 175: yaluy deictic syntax."),
    ("syntax", "Rows 11-20 used bare 1sg A plus one bare reptile object and `nyajil`.", "Rule 175: bare present perception."),
    ("syntax", "Rows 21-30 used bare 2sg A, one bare reptile object, `yinyay`, and `nyajil`.", "Rule 175: yundu yinyay perception."),
    ("syntax", "Rows 31-40 used bare 3pl A, one bare reptile object, `yinyay`, and past `nyajin`.", "Rule 175: jana yinyay past perception."),
    ("syntax", "Rows 41-50 used inclusive `ngana`, one bare reptile object, `yaluy`, and `nyajil`.", "Rule 175: ngana yaluy perception."),
    ("handoff", "Next cadence can consolidate the Rule 175 reptile set, but wrong-marriage, cooking, poisonous, fish/grunter, story/source/use, food, edible, body-part, place, target-case, and event semantics remain closed unless deliberately sourced.", "Rule 175: next cadence."),
]

LEXEMES = [
    ("banamu", "noun", None, "NA", "fresh water snake", "batch-217: selected fresh water snake only; no water-route, bite, poison, food, or event row."),
    ("binju", "noun", None, "NA", "light bellied black snake", "batch-217: selected light bellied black snake only; no wrong-marriage, cooking, or poison row."),
    ("dukul-mukul", "noun", None, "NA", "dukul-mukul lizard", "batch-217: selected dukul-mukul lizard only; no body-part head or size-comparison row."),
    ("jirabay", "noun", None, "NA", "ground lizard", "batch-217: selected ground lizard only; no blue-tongue comparison, ground-place, or movement row."),
    ("junbirr", "noun", None, "NA", "small lizard", "batch-217: selected small lizard only; no wet-season, grass, marking, or body-part row."),
    ("kabuljaka", "noun", None, "NA", "striped water snake", "batch-217: selected striped water snake only; no zebra comparison, water-route, bite, or poison row."),
    ("kulmba-kulmba", "noun", None, "NA", "gecko", "batch-217: selected gecko only; no house-place, smallness predicate, or movement row."),
    ("kurriyala", "noun", None, "NA", "carpet snake", "batch-217: selected carpet snake only; no fish/grunter, story, source-material, belt, or running-from row."),
    ("ngawurr-ngawun", "noun", None, "NA", "freshwater crocodile", "batch-217: selected freshwater crocodile only; no saltwater contrast, attack, hunting, or story row."),
    ("ngumbul", "noun", None, "NA", "sea snake", "batch-217: selected sea snake only; no sea-place, bite, poison, or event row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-217: retained local demonstrative in deictic and supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-217: retained local demonstrative in supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-217: retained past and nonpast perception rows with reptile objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-217: bare pronoun A in present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-217: bare pronoun A in yinyay-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-217: bare pronoun A in yinyay-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-217: bare pronoun A in yaluy-supported present perception rows."),
]


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-217-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 175 rows. Morphology checked bare reptile targets, no target case/compound/possessive/instrument/comitative forms, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected reptile senses and kept rejected candidate, wrong-marriage, cooking, poisonous, fish/grunter, belt/source, running-from, story, story-site, legend, mythological-person, food, edible, eating, hunting, catching, chase, firestick, eye/fighter, place, river, egg, body-part, and target-case traps closed. Syntax checked bare yaluy deictic identification, bare present perception, yinyay-supported present and past perception, and yaluy-supported present perception. Fidelity checked no source-prose use import. Register stayed ordinary reference/perception.",
                 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 locative/dative/ablative/perlative/ergative/instrument/comitative/possessive/privative/excess/reduplicated/compound form, no wrong-marriage/cooking/poison/fish/grunter/story/belt/source/run/food/event claim, and no rejected reptile target.",
                 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 175 lessons covering source checks, rejected candidates, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_217.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 175 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_217.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 217: 50 accepted Rule 175 reptile reference lexical rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_217.py", artifact_path="batch_scripts/close_217.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 = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    under_review_remaining = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    lesson_count = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (batch_id,)).fetchone()[0]
    lexeme_logs = db.execute("SELECT COUNT(*) FROM lexeme_log WHERE detail LIKE '%batch-217:%'").fetchone()[0]
    process_events = db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (LABEL,)).fetchone()[0]
    print(f"closed {LABEL}: 50 accepted rows, {reviews} review passes, {lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, {process_events} process events, under_review={under_review_remaining}, verified corpus={verified}")
    return 0


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