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

NOTES = (
    "CONSTRUCTION: NARRATIVE VERB CASE-FRAME CONSOLIDATION (Rule 118). 50 rows. DESIGN: hand-authored rows "
    "drilling overt followees, left objects/places, taken objects plus source/goal, LOC:pt give/speak/send frames, "
    "babaji-y person-LOC:pt plus topic-DAT frames, material-source ABL, perception objects/sources, laugh targets, "
    "find objects, intransitive wake/rest/weather, and mixed contrast rows. SOURCE CONTROLS: Patz grammar examples "
    "106, 109, 111, 123, 127, 264, 271-274, 283-284, 377-378, 405, 407, 413, 415, 421-423, and Text 3, plus "
    "dictionary.yaml target heads. PROCESS STORAGE: source pass, ambiguity policy, duplicate scan, review corrections, "
    "lint, five-lens review, close, export, docs, and live verification are stored."
)

LESSONS = [
    ("syntax", "`wukurri-l` must keep a followee overt when English has 'follow X'; destination/source can be added separately.", "Rule 118: follow case frame."),
    ("syntax", "`bawa-l` can leave a thing or a place; do not make it an intransitive English-style 'leave' unless the object is recoverable.", "Rule 118: leave object."),
    ("syntax", "`wundi-l` is bring/take and must keep the moved object overt; source/goal case supplies direction.", "Rule 118: wundi object plus case."),
    ("syntax", "`daji-l/daya` recipients are LOC:pt in the sourced give frames.", "Rule 118: dajil recipient."),
    ("syntax", "`balka-l` speech addressees are LOC:pt, while `balka-l` 'make' can take an ABL material source.", "Rule 118: balka-l split."),
    ("syntax", "`babaji-y` is treated by Patz as a fixed intransitive ask-about stem: asker is S/ABS, person asked is LOC:pt, topic is DAT.", "Rule 118: babaji-y frame."),
    ("syntax", "`yunga-l` with a person in LOC:pt is the sourced intermediary frame: translate 'send with X' unless independent evidence supports recipient-only 'to X'.", "Rule 118: yunga-l intermediary."),
    ("morphology", "Common-noun perceivers with `nyaji-l` need ERG A marking; pronoun subjects do not show an ergative contrast.", "Rule 118: perception A marking."),
    ("morphology", "Laugh targets follow the sourced DAT:pt pattern, e.g. `kaykay-anka`; father target is `nganjan-anka`, not LOC:pt `nganjan-anda`.", "Rule 118: laugh target."),
    ("morphology", "`mukul-bama` as transitive A follows the established ERG `mukul-bama-ngka` pattern.", "Rule 118: old-people ERG."),
    ("lexicon", "`madja` is the normalized dictionary/corpus headword for scrub; Patz appendix `maja-nga` is retained only as a quoted source spelling.", "Rule 118: maja/madja policy."),
    ("lexicon", "`ngangkurr` is the noun 'barking noise'; use it as the heard object rather than inventing a bark verb.", "Rule 118: bark sound object."),
    ("lexicon", "`warrmba-bunga-l` is the sourced find verb and should keep a found object visible.", "Rule 118: find object."),
    ("lexicon", "`milka-janay` is used only for concrete listening in this batch, not abstract obedience.", "Rule 118: listen caution."),
    ("lexicon", "`wula-y` rain-stop rows remain cautious extensions from stop/die evidence and should be kept in weather contexts.", "Rule 118: weather stop caution."),
    ("syntax", "Weather predicates take inanimate ABS subjects; do not force ergative morphology onto rain, wind, or thunderstorm rows.", "Rule 118: weather subjects."),
    ("syntax", "Material-source ABL is safe in making/weaving frames when the made object is overt.", "Rule 118: material source."),
    ("fidelity", "Review corrected `yunga-l` English from 'to X' to 'with X' so the translation matches Patz's intermediary examples.", "Rule 118: review correction."),
    ("fidelity", "Review corrected child perception rows to singular ERG `Karrkay-ngku` rather than leaving plural common-noun A unmarked.", "Rule 118: review correction."),
    ("process", "Source ambiguity is not a reason to silently overwrite a row; record the ambiguity and choose a forward policy.", "Rule 118: source ambiguity process."),
    ("process", "Case-frame batches should include explicit contrast rows so LOC:pt person and DAT topic are learned together.", "Rule 118: contrast design."),
    ("process", "Under-review rows can be corrected directly, but every correction must be captured as a process event before close.", "Rule 118: correction logging."),
]

LEXEMES = [
    ("wukurri-l", "transitive-verb", "l", "NA", "follow", "batch-160: followee must be overt; source ex.111."),
    ("bawa-l", "transitive-verb", "l", "NA", "leave; quit", "batch-160: leave object/place plus location."),
    ("wundi-l", "transitive-verb", "l", "NA", "bring; take", "batch-160: moved object plus source/goal case."),
    ("daji-l/daya", "transitive-verb", "l", "NA", "give", "batch-160: LOC:pt recipient and imperative daya."),
    ("yunga-l", "transitive-verb", "l", "NA", "send; allow to go", "batch-160: LOC:pt intermediary, translated 'with X' for source fidelity."),
    ("balka-l", "transitive-verb", "l", "NA", "tell; speak; make", "batch-160: LOC:pt speech addressee and ABL material source."),
    ("babaji-y", "intransitive-verb", "y", "NA", "ask someone about something", "batch-160: fixed intransitive ask-about frame, person LOC:pt, topic DAT."),
    ("nyaji-l", "transitive-verb", "l", "NA", "see; hear; perceive", "batch-160: perception object plus source/location; common noun A marked ERG."),
    ("milka-janay", "intransitive-verb", "y", "NA", "listen; obey", "batch-160: concrete listening only."),
    ("yajarri-l", "intransitive/interaction-verb", "y/l", "NA", "laugh at/about", "batch-160: laugh target DAT:pt, subject ABS/S."),
    ("warrmba-bunga-l", "transitive-verb", "l", "NA", "find", "batch-160: found object remains overt."),
    ("wandi-l", "intransitive-verb", "l", "NA", "get up; wake up; come out", "batch-160: wake/emerge with time/source frames."),
    ("bunda-y", "intransitive-verb", "y", "NA", "sit; stay", "batch-160: posture/stay location."),
    ("warngku wuna-y", "intransitive-verb", "y", "NA", "sleep", "batch-160: sleep compound with location."),
    ("dara-y", "intransitive-verb", "y", "NA", "fall", "batch-160: rain-fall weather predicate."),
    ("kada-y", "intransitive-verb", "y", "NA", "come", "batch-160: movement/weather-event come from source."),
    ("wula-y", "intransitive-verb", "y", "NA", "die; stop", "batch-160: cautious rain-stop weather row."),
    ("yalbay-ma-l", "intransitive-verb", "l", "NA", "become big; rise", "batch-160: water-rise predicate."),
    ("nyunba-y", "intransitive-verb", "y", "NA", "turn back; return", "batch-160: source/location return frames."),
    ("ngangkurr", "noun", None, "NA", "barking noise", "batch-160: heard sound object."),
    ("kudamundu", "locational", None, "NA", "behind", "batch-160: behind follow frame."),
    ("baral", "noun", None, "LOC baral-ba; DAT baral-ka; PERL baral-darr", "road; path", "batch-160: road as left object, location, goal, and path."),
    ("bayan", "noun", None, "LOC bayan-ba; DAT bayan-ka; ABL bayan-muny", "house; camp", "batch-160: house/camp case contrasts."),
    ("bana", "noun", None, "LOC bana-nga; DAT bana-ka; ABL bana-muny", "water", "batch-160: water object/source/topic/goal."),
    ("madja", "noun", None, "LOC madja-nga", "scrub; jungle; rainforest", "batch-160: normalized scrub headword; contrast Patz appendix maja-nga."),
    ("ngalkal", "noun/location", None, "LOC ngalkal-ba", "outside", "batch-160: leave-outside contrast."),
    ("manjal", "noun", None, "ABL manjal-muny", "mountain", "batch-160: weather source."),
    ("wawubaja", "noun", None, "LOC wawubaja-nga", "river", "batch-160: water-rise/find location."),
    ("baya kubu", "compound-noun", None, "NA", "smoke", "batch-160: smoke object in perception row."),
    ("mukul-bama", "noun", None, "ERG mukul-bama-ngka; DAT mukul-bama-nka", "old people", "batch-160: ERG correction and S frames."),
    ("nganjan-anka", "case-form", None, "DAT:pt", "father-DAT target", "batch-160: laugh target correction."),
    ("mayi-ka", "case-form", None, "DAT", "food-DAT", "batch-160: retained DAT harmony lesson from Batch 159 repair."),
]


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-160-verify", note, NOW),
        )
    record_event(
        db,
        batch_label=LABEL,
        phase="lint",
        event_type="pre-close-lint-pass",
        actor="claude-main",
        detail=(
            "After review corrections, full-corpus lint passed under review: 8097 rows scanned, "
            "0 issues flagged; accepted goal metric correctly remained 8047 until close."
        ),
        command="python3 lint_corpus.py",
        output_excerpt="lint: 8097 rows scanned, 0 issues flagged; GOAL METRIC: 8047 / 20000 verified sentences (91894 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 118 rows after corrections. Morphology checked ERG/ABS marking, "
            "LOC:pt/DAT/ABL/PERL forms, y/l-conjugation past/nonpast, DAT harmony, and old-people ERG. Lexicon checked "
            "every content word against dictionary.yaml or Patz examples. Syntax checked overt objects for transitive verbs, "
            "fixed-intransitive babaji-y, yunga-l intermediary frames, and inanimate weather subjects. Fidelity corrected "
            "send-with, perception A marking, laugh target, and mukul-bama-ngka. Register stayed practical narrative-style "
            "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=(
            "Rejected-risk decisions retained: no new vocabulary, no Rule 116 clitic reuse, no ergative askers for babaji-y, "
            "no recipient-only translation for sourced yunga-l intermediary rows, no unmarked common-noun perceiver A, "
            "no LOC:pt laugh target where DAT:pt is sourced, and no new maja-nga scrub rows."
        ),
        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 118 lessons covering case frames, corrections, source ambiguity, and process safeguards.",
        artifact_path="batch_scripts/close_160.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 118 narrative case-frame vocabulary and case forms.",
        artifact_path="batch_scripts/close_160.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 160: 50 accepted Rule 118 case-frame rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_160.py",
        artifact_path="batch_scripts/close_160.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-160-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())
