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

NOTES = (
    "CONSTRUCTION: CASE-FRAME CONSOLIDATION AFTER RULE 125 (Rule 126). 50 rows. DESIGN: hand-authored consolidation "
    "of Rule 125 heads inside retained case frames, with no new lexical heads and no new morphology. SOURCE CONTROLS: "
    "kaba kept in weather/fall frame; kija restricted to moon; dawar star; wangal boomerang noun; warrbi axe; "
    "naybu/marrkin/mayngku/wulman loan-logged; biyul and baral-muny excluded. REVIEW: duplicate row 45 repaired "
    "before banking and marginal weather-source row tightened to Kaba bayan-ba daran. PROCESS STORAGE: source readback, "
    "duplicate scan, static guards, lint, review, close, export, docs, and live checks are stored as process evidence."
)

LESSONS = [
    ("process", "A consolidation batch should reuse the prior lexical set and stress known frames, not admit new heads.", "Rule 126: construction cadence."),
    ("process", "Exact-surface duplicate scans remain necessary for maintenance rows; Batch 168 repaired a kambi-ji duplicate before banking.", "Rule 126: duplicate scan."),
    ("process", "Marginal semantic extensions should be tightened before banking; Batch 168 replaced a rain-from-sea row with a safer rain-fell-at-camp row.", "Rule 126: weather-frame tightening."),
    ("process", "Process evidence should store rejected draft decisions as well as final accepted rows, because they explain why the corpus stayed conservative.", "Rule 126: process retention."),
    ("lexicon", "`kuyu` and `minya` are safe in rest, placement/source, and perception rows when their object status remains explicit.", "Rule 126: food heads."),
    ("lexicon", "`kaba` should remain in weather predicates such as `dara-y` and `kada-y`; avoid unsourced source-motion elaborations.", "Rule 126: kaba weather discipline."),
    ("lexicon", "`kija` remains moon/month only and `dawar` remains the safe star lexeme.", "Rule 126: sky noun discipline."),
    ("lexicon", "`wangal` remains boomerang noun and `warrbi` remains axe in this corpus slice.", "Rule 126: sense discipline."),
    ("lexicon", "`naybu`, `marrkin`, `mayngku`, and `wulman` are loan/contact forms that must be transparent in `loans_used`.", "Rule 126: loan transparency."),
    ("lexicon", "`kalka`, `mirru`, and `kunjuri` are safe as ABS objects or rest subjects here, not as newly derived instruments or comitatives.", "Rule 126: implement nouns."),
    ("morphology", "Retained LOC, ABL, and DAT forms can be recombined conservatively when the source frame is already known.", "Rule 126: case recombination."),
    ("morphology", "No new instrument, comitative, or possessive forms were coined from the tool/weapon nouns.", "Rule 126: no new analogy."),
    ("morphology", "The closed comitative set remains `ngawa-nji`, `jawun-unji`, `nganjan-anji`, `juku-ji`, and `kambi-ji`.", "Rule 126: closed comitatives."),
    ("morphology", "`bunday` with a comitative keeps the place-before-comitative order used in the repaired Rule 125 row.", "Rule 126: bunday order."),
    ("syntax", "Common-noun `nyaji-l` perceivers remain ERG-marked, while matched pronoun A rows remain bare.", "Rule 126: perception contrast."),
    ("syntax", "`babaji-y` ask-about rows retain ABS/S asker, LOC:pt person asked, and DAT topic.", "Rule 126: ask-about syntax."),
    ("syntax", "`yajarri-l` laugh rows require an explicit DAT:pt target suffix; comitative forms must not be repurposed as targets.", "Rule 126: laugh target syntax."),
    ("syntax", "`wundi-l` transfer rows keep source/goal phrases transparent, especially with bare pronoun A.", "Rule 126: transfer syntax."),
    ("fidelity", "Batch 168 prefers semantically ordinary rows over clever coverage; the weather repair is the model for future marginal cases.", "Rule 126: fidelity standard."),
    ("register", "The batch stays plain, practical, and elder-verification pending: food, weather, tools, seeing, asking, laughing, and moving with companions.", "Rule 126: register scope."),
]

LEXEMES = [
    ("kuyu", "noun", None, "NA", "fish", "batch-168: consolidated as rest subject, placed object, and perceived object."),
    ("minya", "noun", None, "NA", "meat; flesh food; animal", "batch-168: consolidated as rest subject, object/source object, perceived object, and DAT topic."),
    ("kaba", "noun", None, "NA", "rain", "batch-168: kept in weather/fall frame, not source-motion extension."),
    ("dawar", "noun", None, "NA", "star", "batch-168: safe star lexeme retained."),
    ("kija", "noun", None, "NA", "moon; month", "batch-168: moon sense only."),
    ("warrbi", "noun", None, "NA", "axe", "batch-168: axe sense only."),
    ("naybu", "noun", None, "NA", "knife", "batch-168: source-backed English loan, used as ABS/rest or object."),
    ("kalka", "noun", None, "NA", "fishing spear; spear", "batch-168: clean spear head retained instead of excluded biyul."),
    ("mirru", "noun", None, "NA", "club; nullanulla", "batch-168: club rest/object/goal rows."),
    ("kunjuri", "noun", None, "NA", "shield", "batch-168: shield rest/source/leave rows."),
    ("wangal", "noun", None, "NA", "boomerang", "batch-168: boomerang noun only."),
    ("marrkin", "noun", None, "NA", "gun; rifle", "batch-168: source-backed musket/rifle loan used as ABS/rest or object."),
    ("wabarr-ba", "case-form", None, "LOC", "in the shade", "batch-168: retained shade LOC in rest, object, perception, comitative, and gun rows."),
    ("balji-nga", "case-form", None, "LOC", "in the bag", "batch-168: retained bag LOC with meat rest/object/perception."),
    ("ngalkal-ba", "case-form", None, "LOC", "outside", "batch-168: retained outside LOC with tools, sky nouns, comitatives, and staying row."),
    ("bubu-ngu", "case-form", None, "LOC", "on the ground", "batch-168: retained ground LOC with knife, shield, fish placement, and boomerang perception."),
    ("baral-ba", "case-form", None, "LOC", "on/to the road", "batch-168: retained road LOC with spear and father-comitative row."),
    ("bayan-ba", "case-form", None, "LOC", "at camp/house", "batch-168: retained camp LOC in the tightened weather row."),
    ("bayan-ka", "case-form", None, "DAT", "to/about camp or house", "batch-168: retained DAT goal with knife and club transfer rows."),
    ("bayan-muny", "case-form", None, "ABL", "from house/camp", "batch-168: retained ABL source with shield, meat, and axe transfer rows."),
    ("jalun-bu", "case-form", None, "LOC", "at/to the sea", "batch-168: retained sea LOC in friend-comitative motion row."),
    ("minya-ka", "case-form", None, "DAT", "about meat", "batch-168: retained grammar-sourced meat DAT topic."),
    ("kuku-ku", "case-form", None, "DAT", "about news/language", "batch-168: retained news/language DAT topic."),
    ("mayngku-ku", "case-form", None, "DAT", "about mango", "batch-168: retained mango DAT topic."),
    ("babi-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandmother", "batch-168: person target/person-asked form in ask and laugh rows."),
    ("kami-nda", "case-form", None, "LOC:pt/DAT:pt", "at/to grandfather", "batch-168: person target/person-asked form in ask and laugh rows."),
    ("ngamu-ndu", "case-form", None, "LOC:pt/DAT:pt", "at/to mother", "batch-168: person target/person-asked form in ask and laugh rows."),
    ("nganjan-anda", "case-form", None, "LOC:pt", "at/to father", "batch-168: person asked form in mango-topic row."),
    ("maral-anda", "case-form", None, "LOC:pt/DAT:pt", "at/to the girl", "batch-168: person target/person-asked form in ask and laugh rows."),
    ("ngawa-nji", "case-form", None, "COMIT:pt", "with the baby", "batch-168: closed-comitative member retained."),
    ("jawun-unji", "case-form", None, "COMIT:pt", "with a friend", "batch-168: closed-comitative member retained."),
    ("nganjan-anji", "case-form", None, "COMIT:pt", "with father", "batch-168: closed-comitative member retained."),
    ("juku-ji", "case-form", None, "COMIT", "with a stick", "batch-168: closed-comitative member retained."),
    ("kambi-ji", "case-form", None, "COMIT", "with clothes", "batch-168: closed-comitative member retained after duplicate repair."),
    ("wuna-y", "verb", "y", "NA", "lie", "batch-168: rest rows with Rule 125 heads."),
    ("dara-y", "verb", "y", "NA", "fall", "batch-168: tightened rain weather row."),
    ("yijarri-l", "verb", "l", "NA", "put", "batch-168: placement rows with fish, meat, and spear."),
    ("bawa-l", "verb", "l", "NA", "leave", "batch-168: leave rows with axe, knife, boomerang, gun, and shield."),
    ("wundi-l", "verb", "l", "NA", "bring; take", "batch-168: transfer rows with shield, meat, knife, club, and axe."),
    ("mani-l", "verb", "l", "NA", "get", "batch-168: club object outside."),
    ("nyaji-l", "verb", "l", "NA", "see; hear", "batch-168: perception rows with common-noun/pronoun contrasts."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-168: ask-about rows with retained DAT topics."),
    ("yajarri-l", "verb", "l", "NA", "laugh at/about", "batch-168: laugh-target rows with DAT:pt targets."),
    ("dunga-y", "verb", "y", "NA", "go", "batch-168: closed-comitative motion rows."),
    ("bunday", "verb", "y", "NA", "stay; sit", "batch-168: 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-168-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="under-review-lint-green",
        actor="claude-main",
        detail="After banking, lint scanned 8,497 rows and found 0 issues; verified total remained 8,447 before close.",
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8497 rows scanned, 0 issues flagged; GOAL METRIC: 8447 / 20000 verified sentences (93384 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 126 rows. Morphology checked retained LOC, ABL, DAT, "
            "LOC:pt/DAT:pt, COMIT, ERG, past, and nonpast forms, with no new instrument/comitative/possessive "
            "analogy. Lexicon checked every foregrounded head and loan flag. Syntax checked rest, placement, "
            "transfer source/goal, common-noun ERG perception A, bare pronoun A, ask-about rows, laugh targets, "
            "and closed comitatives. Fidelity checked the duplicate repair and weather-frame tightening. Register "
            "remained plain practical speech pending elder verification."
        ),
        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: no new heads; no biyul; no baral-muny; kaba kept in dara-y weather "
            "frame; kija moon/month only; dawar star; wangal boomerang noun; warrbi axe; loan flags for naybu, marrkin, "
            "mayngku, and wulman; common-noun nyaji-l perceivers ERG-marked; babaji-y askers not ERG-marked; yajarri-l "
            "targets DAT:pt; comitatives limited to the closed sourced set."
        ),
        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 126 lessons covering process, lexical senses, morphology, syntax, fidelity, and register.",
        artifact_path="batch_scripts/close_168.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 126 heads, case forms, target forms, comitatives, and predicates.",
        artifact_path="batch_scripts/close_168.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 168: 50 accepted Rule 126 consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_168.py",
        artifact_path="batch_scripts/close_168.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-168-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())
