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

NOTES = (
    "CONSTRUCTION: INANIMATE POSSESSOR, MATERIAL-SOURCE, OBJECT-LOCATION, AND ATTRIBUTIVE COMITATIVE CASE "
    "ALTERNATIONS (Rule 110). 50 rows. DESIGN: construction batch after Rule 109 plant/material lexicon. SOURCE "
    "CONTROLS: Patz §4.5.3 inanimate possessor, §4.5.5 possessive-locative relationship, §3.2.3.2 possessive "
    "allomorphy, §3.2.3.3 comitative allomorphy, §4.6.1 comitative attributes, exx.524-526, 531-546. PROCESS "
    "STORAGE: source pass, blocked-case controls, duplicate preflight, lint outputs, five-lens review, close, export, "
    "and live-doc verification are stored in process_events and the batch process log."
)

LESSONS = [
    ("syntax", "Inanimate possessor with real location commonly uses locative: birra juku-ngu, nganka juku-ngu, dingal juku-ngu.", "Rule 110: inanimate possessor locative."),
    ("syntax", "Inanimate possessor with origin/source uses ablative: birra juku-muny, walmba juku-muny, bindi juku-muny.", "Rule 110: inanimate possessor ablative."),
    ("syntax", "Do not generalize ablative blindly: Patz explicitly rejects marra-muny in the dumbul marra-nga/-mu/*-muny shell-of-zamia frame.", "Rule 110: blocked marra-muny."),
    ("syntax", "Possessive is possible but less common for inanimate possessors; Batch 152 uses marra-mu only in the source-backed zamia-shell frame.", "Rule 110: sparse inanimate possessive."),
    ("morphology", "Container and object alternations pair LOC for current location with ABL for source: dubal-ba/dubal-muny, balji-nga/balji-muny, kurmun-ba/kurmun-muny, bayan-ba/bayan-muny.", "Rule 110: LOC vs ABL object pairs."),
    ("morphology", "Material-source rows use -muny on the material, not locative: duwar-muny, kuralbi-muny, bilanji-muny, mawu-muny, kakan-muny, nganjirr-muny.", "Rule 110: material-source -muny."),
    ("syntax", "A single row can contrast material origin and current location: kanunjul nganjirr-muny kalka-nga yinyay.", "Rule 110: origin plus location."),
    ("morphology", "Neutral comitative zero-inflection uses -ji after most stems and -iji after rhotic stems: birra-ji, nganka-ji, balji-ji, diburr-iji.", "Rule 110: zero comitative allomorphy."),
    ("morphology", "Case-stacked attributive comitative uses -jirr before non-zero case with stop/m suffixes: birra-jirr-ka, nganka-jirr-ka, mayi-jirr-ka, juku-jirr-muny.", "Rule 110: nonzero comitative allomorphy."),
    ("syntax", "Attributive comitative is characteristic, not ownership alone: yinya juku birra-ji means a leaf-bearing tree; yinya dingkar kalka-ji wubul-ji means spear-having as a characteristic.", "Rule 110: comitative characteristic."),
    ("syntax", "Comitative attributes agree with the wider NP case in source-shaped rows: kaya-ngka kuli-ji-ngka, dingkar-angka walarr-iji-ngka.", "Rule 110: comitative case agreement."),
    ("syntax", "Dative heads can carry comitative dative attributes after verbs like wawu and binal: juku-ku birra-jirr-ka, kalka-ka kanunjul-jirr-ka.", "Rule 110: DAT head plus COMIT-DAT."),
    ("syntax", "Ablative heads can carry comitative ablative attributes: bayan-muny juku-jirr-muny, bayan-muny buyku-jirr-muny.", "Rule 110: ABL head plus COMIT-ABL."),
    ("lexicon", "Barka remains excluded because the dictionary conflict is lexical, not case-marking; do not reintroduce it in construction batches.", "Rule 110: barka exclusion carried."),
    ("lexicon", "Marra remains zamia tree/nut/wing; in this rule the source-backed frame is dumbul marra-nga/-mu, not marra-muny.", "Rule 110: marra sense plus case guard."),
    ("process", "Construction batches can still collide with earlier source rows; Batch 152 duplicate preflight replaced three source-shaped surfaces before banking.", "Rule 110: duplicate preflight."),
]

LEXEMES = [
    ("birra", "noun", None, "LOC/ABL host frames; COMIT birra-ji/-jirr-ka", "leaf; lungs", "batch-152: leaf sense in LOC/ABL and comitative rows."),
    ("juku", "noun", None, "locative-ngu/ablative-muny/dative-ku", "tree; wood; splinter", "batch-152: host, source, dative head, and comitative attribute base."),
    ("nganka", "noun", None, "COMIT nganka-ji/-jirr-ka", "flower; blossom", "batch-152: flowers on tree and flower-COMIT rows."),
    ("jurrbu", "noun", None, "NA", "plant shoots", "batch-152: shoots on tree locative row."),
    ("bindi", "noun", None, "NA", "broad leaf", "batch-152: source-from-tree plus bag-location rows."),
    ("dakil-dakil", "noun", None, "NA", "branches of a tree", "batch-152: tree-part locative row."),
    ("dingal", "noun", None, "NA", "base of tree; end", "batch-152: base-on-that-tree locative row."),
    ("wakumba", "noun", None, "NA", "canopy; spreading branches", "batch-152: canopy-on-that-tree locative row."),
    ("walmba", "noun", None, "NA", "log", "batch-152: log from tree plus ground locative row."),
    ("dimbirr", "noun", None, "NA", "hollow trunk of a tree", "batch-152: tree-part locative row."),
    ("jakalkulu", "noun", None, "NA", "tree stump", "batch-152: stump on ground locative row."),
    ("mayi", "noun", None, "COMIT mayi-jirr-ka", "vegetable food; fruit; food", "batch-152: fruit-on/from-tree and fruit-COMIT dative attribute."),
    ("kabal", "noun", None, "NA", "Leichhardt tree; Leichhardt fruit", "batch-152: mayi kabal in good-to-eat locative/ablative frames."),
    ("dumbul", "noun", None, "NA", "hard covering; bark; shell; crust", "batch-152: zamia-shell locative/possessive frame."),
    ("marra", "noun", None, "LOC marra-nga; POSS marra-mu; blocked ABL marra-muny", "zamia tree; zamia nut; wing", "batch-152: source-backed zamia-shell frame only."),
    ("dubal", "noun", None, "locative-ba/ablative-muny", "bark; coolamon; bark container", "batch-152: container LOC/ABL pair and bark-from-tree row."),
    ("diburr", "noun", None, "COMIT diburr-iji", "seed; egg; bullet; tablet", "batch-152: seed sense in bag/location and comitative row."),
    ("balji", "noun", None, "locative-nga/ablative-muny/COMIT balji-ji", "bag; dillybag", "batch-152: container pair and bag-COMIT row."),
    ("karra", "noun", None, "NA", "rope; cord; string", "batch-152: sack LOC/ABL pair and material-source object."),
    ("kurmun", "noun", None, "locative-ba/ablative-muny", "sack; bag", "batch-152: sack LOC/ABL source pair."),
    ("bulin", "noun", None, "NA", "plate", "batch-152: post-contact object in house LOC/ABL pair."),
    ("naybu", "noun", None, "NA", "knife", "batch-152: attested loan in bag LOC/ABL pair."),
    ("duwar", "noun", None, "ablative-muny", "black palm", "batch-152: material source for spear."),
    ("kuralbi", "noun", None, "ablative-muny", "kuralbi tree; wild peasun; bark rope source", "batch-152: material source for rope."),
    ("bilanji", "noun", None, "ablative-muny", "grass used for dilly bags", "batch-152: material-source ABL row."),
    ("mawu", "noun", None, "ablative-muny", "coarse grass used in dilly bags", "batch-152: material-source ABL row."),
    ("kakan", "noun", None, "ablative-muny", "green upper part of black palm used for dilly bags", "batch-152: prose-backed material-source ABL row."),
    ("kanunjul", "noun", None, "COMIT kanunjul-jirr-ka", "grass-tree resin; pitch", "batch-152: source plus location and COMIT-DAT rows."),
    ("nganjirr", "noun", None, "ablative-muny", "grass tree", "batch-152: source tree for kanunjul."),
    ("buyku", "noun", None, "COMIT buyku-jirr-muny", "paperbark", "batch-152: COMIT-ABL attribute row."),
    ("kaya", "noun", None, "ERG:pt kaya-ngka", "dog", "batch-152: ERG head with kuli-ji-ngka attribute."),
    ("kuli", "noun", None, "COMIT kuli-ji/kuli-ji-ngka", "rage; anger", "batch-152: vicious/wild comitative attribute with degree."),
    ("dingkar", "noun", None, "ERG:pt dingkar-angka", "man", "batch-152: human head in comitative possession/ERG rows."),
    ("walarr", "noun", None, "COMIT walarr-iji/-iji-ngka", "beard; whiskers", "batch-152: source-backed beard-COMIT rows."),
    ("kalka", "noun", None, "DAT kalka-ka; COMIT kalka-ji", "spear", "batch-152: spear possession, dative head, and material-source object."),
    ("wubul", "quantifier", None, "COMIT wubul-ji", "many; much", "batch-152: many-COMIT in possession-as-characteristic row."),
    ("wawu", "verb", None, "NA", "like; want", "batch-152: takes DAT head plus COMIT-DAT attribute."),
    ("binal", "verb", None, "NA", "know", "batch-152: takes DAT head plus COMIT-DAT attribute."),
    ("babaji", "verb", None, "NA", "ask", "batch-152: ask-about frame with DAT head plus COMIT-DAT attribute."),
]


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-152-verify", note, 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 110 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to LOC-vs-ABL inanimate possessor frames, the blocked marra-muny form, sparse "
            "inanimate possessive marra-mu, material-source -muny, container LOC/ABL pairs, zero and non-zero "
            "comitative allomorphs, comitative case agreement, loan restraint, and exact duplicate avoidance."
        ),
        artifact_path="process_logs/batch-152-case-alternations-process.md",
        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 152: 50 accepted Rule 110 case-alternation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_152.py",
        artifact_path="batch_scripts/close_152.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]
    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-152-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, verified corpus={verified}"
    )
    return 0


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