#!/usr/bin/env python3
"""Close batch-167 after main-loop five-lens review."""

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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-167"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
PROCESS_LOG = "process_logs/batch-167-source-backed-lexical-expansion-after-rule124-process.md"
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "LEXICAL: SOURCE-BACKED LEXICAL EXPANSION AFTER RULE 124 (Rule 125). 50 rows. DESIGN: hand-authored small "
    "lexical expansion using kuyu, minya, kaba, dawar, kija, warrbi, naybu, kalka, mirru, kunjuri, wangal, and "
    "marrkin inside retained Rule 124 case frames. SOURCE CONTROLS: exact dictionary/grammar readback for every "
    "foregrounded head; biyul excluded for dialect/source caution; kija restricted to moon; wangal as boomerang noun; "
    "warrbi as axe; naybu/marrkin logged as loans. REVIEW: four duplicate surfaces repaired before banking and one "
    "under-review row-order repair restored place-before-comitative order. PROCESS STORAGE: source readback, duplicate "
    "scan, static guards, lint, review, close, export, docs, and live checks are stored as process evidence."
)

LESSONS = [
    ("process", "A lexical batch should admit a small set of heads and reuse old frames, not widen the morphology.", "Rule 125: small lexical expansion."),
    ("process", "Exact-surface duplicate scans are needed even for frame-maintenance rows; Batch 167 repaired four planned duplicates before banking.", "Rule 125: duplicate scan."),
    ("process", "Under-review review may catch source-order issues that lint cannot; Batch 167 repaired the `bundanday ngawa-nji` row before close.", "Rule 125: source-order repair."),
    ("lexicon", "`biyul` was checked but excluded because the dictionary entry carries a Nyungkal/Yalanji caution; `kalka` is the cleaner spear head here.", "Rule 125: biyul exclusion."),
    ("lexicon", "`kuyu` is generic fish and is safe as rest subject, moved object, perceived object, and sea-source object.", "Rule 125: kuyu source."),
    ("lexicon", "`minya` is meat/flesh food/animal and also has the directly sourced DAT topic `minya-ka`.", "Rule 125: minya source."),
    ("lexicon", "`kaba` is rain; Batch 167 uses the grammar-backed `kaba kada-y` frame.", "Rule 125: kaba source."),
    ("lexicon", "`kija` is moon/month only in this batch; never use it for cold or other senses.", "Rule 125: kija guard."),
    ("lexicon", "`dawar` is the safe star lexeme and continues the anti-phantom star ruling.", "Rule 125: dawar guard."),
    ("lexicon", "`warrbi` is used as axe only; the grass-house sense is out of scope here.", "Rule 125: warrbi sense."),
    ("lexicon", "`wangal` is boomerang noun, not a dance verb.", "Rule 125: wangal sense."),
    ("lexicon", "`naybu` and `marrkin` are source-backed loans and must be marked in `loans_used` when foregrounded.", "Rule 125: loan transparency."),
    ("morphology", "New tool/weapon nouns entered as ABS objects; Batch 167 did not create new instruments, comitatives, or case forms from them.", "Rule 125: no new case analogy."),
    ("morphology", "`minya-ka`, `kuku-ku`, and `mayngku-ku` are sourced DAT topics in ask-about rows.", "Rule 125: DAT topic discipline."),
    ("morphology", "The closed comitative set remains `ngawa-nji`, `jawun-unji`, `nganjan-anji`, `juku-ji`, and `kambi-ji`.", "Rule 125: closed comitatives."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked with the new fish, meat, knife, axe, moon, and star objects.", "Rule 125: perception A marking."),
    ("syntax", "Pronoun A remains bare in matched perception and transfer rows.", "Rule 125: pronoun A continuity."),
    ("syntax", "`babaji-y` ask-about rows keep ABS/S asker, LOC:pt person, and DAT topic; the duplicate repairs did not change that frame.", "Rule 125: ask-about syntax."),
    ("syntax", "`yajarri-l` laugh targets keep DAT:pt targets, even when duplicates are repaired by changing participants.", "Rule 125: laugh target continuity."),
    ("register", "The batch remains plain and source-grounded: food, rain/sky, implements, and ordinary participant interactions, pending elder verification.", "Rule 125: register scope."),
]

LEXEMES = [
    ("kuyu", "noun", None, "NA", "fish", "batch-167: foregrounded as fish in rest, object, source, and perception rows."),
    ("minya", "noun", None, "NA", "meat; flesh food; animal", "batch-167: foregrounded as meat/flesh food and DAT topic."),
    ("kaba", "noun", None, "NA", "rain", "batch-167: used only in grammar-backed rain came frame."),
    ("dawar", "noun", None, "NA", "star", "batch-167: safe star lexeme retained."),
    ("kija", "noun", None, "NA", "moon; month", "batch-167: moon sense only; cold/place senses excluded."),
    ("warrbi", "noun", None, "NA", "axe", "batch-167: axe sense only, not grass-house sense."),
    ("naybu", "noun", None, "NA", "knife", "batch-167: source-backed English loan used as ABS object, not new instrument."),
    ("kalka", "noun", None, "NA", "fishing spear; spear", "batch-167: clean spear head used instead of excluded biyul."),
    ("mirru", "noun", None, "NA", "club; nullanulla", "batch-167: club object in rest, source, and goal rows."),
    ("kunjuri", "noun", None, "NA", "shield", "batch-167: shield object in rest/get/leave rows."),
    ("wangal", "noun", None, "NA", "boomerang", "batch-167: boomerang noun only, not dance verb."),
    ("marrkin", "noun", None, "NA", "gun; rifle", "batch-167: source-backed loan from musket/rifle used as ABS object."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-167: retained bag LOC with fish and knife."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-167: retained shade LOC with meat, father-comitative, old-man staying row, and shield."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-167: retained ground LOC with axe, boomerang, and meat perception."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-167: retained outside LOC with spear, shield, axe, sky nouns, friend comitative, and gun."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-167: retained road LOC with club and closed comitatives; no baral-muny."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-167: retained camp LOC with gun and shield."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-167: retained DAT goal with gun and club."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-167: retained ABL source with club and boomerang."),
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-167: retained sea LOC in fish perception and baby-comitative rows."),
    ("jalun-muny", "case-form", None, "ABL", "from the sea", "batch-167: retained sea ABL with fish transfer."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-167: grammar-sourced meat DAT topic in ask-about rows."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-167: retained news/language DAT topic."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-167: retained mango DAT topic."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-167: closed-comitative member retained."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-167: closed-comitative member retained."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-167: closed-comitative member retained."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-167: closed-comitative member retained."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-167: closed-comitative member retained."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-167: rest rows with new lexical heads."),
    ("kada-y", "verb", "y", "NA", "come", "batch-167: rain came and retained source rows."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-167: placement rows with new objects."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-167: leave rows with meat, spear, boomerang, shield, and gun."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-167: transfer rows with club, fish, gun, boomerang, and club goal."),
    ("mani-l", "verb", "l", "NA", "get", "batch-167: shield object at camp."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-167: perception rows with new lexical objects and sky nouns."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-167: ask-about rows with minya-ka, kuku-ku, mayngku-ku."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-167: laugh-target rows with duplicate-safe targets."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-167: closed-comitative motion rows."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-167: repaired place-before-comitative staying row."),
]


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}")

    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-167-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After the row-46 source-order repair and rebank, lint scanned 8,447 rows and found 0 issues; verified total remained 8,397 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8447 rows scanned, 0 issues flagged; GOAL METRIC: 8397 / 20000 verified sentences (93200 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 125 rows after row 46 was repaired and rebanked. Morphology "
            "checked retained LOC, ABL, DAT, DAT:pt, LOC:pt, COMIT, ERG, past, and nonpast forms, with no new case "
            "analogy from tool/weapon nouns. Lexicon checked every foregrounded head against dictionary/Patz evidence "
            "and retained sense restrictions. Syntax checked object visibility, common-noun ERG perception A, bare "
            "pronoun A, ask-about, laugh targets, transfer source/goal, and closed comitative frames. Fidelity checked "
            "kija moon-only, dawar star, wangal noun, warrbi axe, loan transparency, biyul exclusion, and row-46 order. "
            "Register stayed plain food/weather/sky/implement and participant interaction."
        ),
        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 these decisions: biyul excluded; kija moon/month only; dawar star; wangal boomerang "
            "noun; warrbi axe; naybu and marrkin logged as loans; no new instruments/comitatives/possessives; no "
            "baral-muny; no ergative babaji-y askers; common-noun nyaji-l perceivers ERG-marked; yajarri-l targets DAT:pt."
        ),
        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 125 lessons covering process, lexical senses, morphology, syntax, and register.",
        artifact_path="batch_scripts/close_167.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 125 heads, case forms, DAT topics, comitatives, and predicates.",
        artifact_path="batch_scripts/close_167.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 167: 50 accepted Rule 125 lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_167.py",
        artifact_path="batch_scripts/close_167.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 action='batch-167-verify'").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, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, "
        f"{process_events} process events, under_review={under_review_remaining}, "
        f"verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
