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

NOTES = (
    "AUDIBLE-SOUND REFERENCE LEXICAL EXPANSION AFTER RULE 200 (Rule 201). 50 rows. TARGETS: kawal cooee, "
    "ngawungkal halloo, ngulnkul hum, nyinja grunt, wungka wail, kandarr belch, ngangkun hiccups, wankun "
    "hiccoughs, warimaji yawn, and kunji sneeze. FRAMES: Ngayu TARGET nyajil, Yundu TARGET yinyay nyajil, "
    "Jana TARGET yinyay nyajin, Ngana TARGET yaluy nyajil, and Ngayu yinya TARGET nyajil. REVIEW: nyaji-l was "
    "used only in its sourced hear/heard sense; all targets stayed bare sound nouns; pronoun A stayed bare; "
    "yaluy/yinyay/yinya stayed support only. No previous sound-batch heads, sound-making verbs, source persons/"
    "animals, dog/pig/motor/food sources, chewing/noisy-eating row, woman-in-distress narrative, mourning/death "
    "story, sickness/illness diagnosis, body-part possession, target-case, compound, plural, derivation, productive "
    "reduplication, tree-reference, or demonstrative-inflection row was opened."
)

LESSONS = [
    ("process", "Rule 201 returned to lexical expansion after Rule 200 and selected ten unused audible-sound/body-sound nouns.", "Rule 201: lexical cadence after Rule 200."),
    ("process", "The field was deliberately sound-reference only, because sound nouns easily invite source-person, animal, illness, food, distress, and event expansions.", "Rule 201: sound-reference restraint."),
    ("process", "Exact duplicate preflight over all 50 planned sound-reference surfaces returned no cross-corpus accepted/revised/under_review collisions.", "Rule 201: duplicate preflight."),
    ("source", "Patz example 109 supports nyaji-l with an audible object in the sense 'hear'.", "Rule 201: nyaji-l hear source."),
    ("source", "Patz example 457 and the nyajil dictionary entry support hear/heard as part of the general perception verb.", "Rule 201: hearing perception support."),
    ("source", "Patz 4.2.1 supports pronoun experiencers as A arguments in sensory-perception clauses; pronouns stay bare.", "Rule 201: pronoun A in hearing clauses."),
    ("lexicon", "Kawal was admitted only as cooee, not as an event of shouting or a source person.", "Rule 201: kawal cooee only."),
    ("lexicon", "Ngawungkal was admitted only as halloo, not as a far-away source-person event.", "Rule 201: ngawungkal halloo only."),
    ("lexicon", "Ngulnkul was admitted only as hum, not as a productive humming/tune-making event.", "Rule 201: ngulnkul hum only."),
    ("lexicon", "Nyinja was admitted only as grunt, not as a pig/animal-source or grunting event row.", "Rule 201: nyinja grunt only."),
    ("lexicon", "Wungka was admitted only as wail, not as woman-in-distress, screaming, swearing, mourning, or narrative content.", "Rule 201: wungka wail only."),
    ("lexicon", "Kandarr was admitted only as belch/burp, not as a body-state or source-person event.", "Rule 201: kandarr belch only."),
    ("lexicon", "Ngangkun was admitted only as hiccups/hiccoughs, not as illness or diagnosis.", "Rule 201: ngangkun hiccups only."),
    ("lexicon", "Wankun was admitted only as hiccoughs, not as illness or diagnosis.", "Rule 201: wankun hiccoughs only."),
    ("lexicon", "Warimaji was admitted only as yawn, not as an event caused by a person or sleep state.", "Rule 201: warimaji yawn only."),
    ("lexicon", "Kunji was admitted only as sneeze, not as sickness or fire homograph drift.", "Rule 201: kunji sneeze only."),
    ("lexicon", "Previous sound heads jangkuy, kankar, nginja, numburr, yanja, kadil, kuwimbur, ngangkurr, and ngingkirr stayed closed.", "Rule 201: previous sound-batch heads closed."),
    ("morphology", "All sound targets stayed bare: no target locative, dative, ablative, perlative, ergative, instrumental, comitative, possessive, privative, degree, plural, compound, derivation, or productive reduplication.", "Rule 201: bare target morphology."),
    ("morphology", "Nyaji-l tense stayed consistent: nonpast nyajil and past nyajin with analysis nyaji-l and nyaji-ny.", "Rule 201: hearing tense discipline."),
    ("morphology", "Pronoun A heads ngayu, yundu, jana, and ngana stayed bare.", "Rule 201: pronoun A discipline."),
    ("syntax", "Rows 1-10 used Ngayu TARGET nyajil.", "Rule 201: 1sg hear frame."),
    ("syntax", "Rows 11-20 used Yundu TARGET yinyay nyajil.", "Rule 201: 2sg hear-there frame."),
    ("syntax", "Rows 21-30 used Jana TARGET yinyay nyajin.", "Rule 201: 3pl heard-there frame."),
    ("syntax", "Rows 31-40 used Ngana TARGET yaluy nyajil.", "Rule 201: 1pl hear-here frame."),
    ("syntax", "Rows 41-50 used Ngayu yinya TARGET nyajil, retaining Rule 200 distal demonstrative support without adding demonstrative morphology.", "Rule 201: 1sg hear-that frame."),
    ("fidelity", "English stayed literal and reference-only: hear/heard plus the selected sound noun and optional here/there/that support.", "Rule 201: literal English."),
    ("fidelity", "No English source person/animal, dog, pig, motor, food, chewing, shouting event, singing event, illness, distress, mourning, death, body-part, place, country, tree, material, or making wording was imported.", "Rule 201: denied English fields."),
    ("register", "Rows remained plain hearing/perception clauses, not social, illness, bodily-source, mourning, animal, food, or sound-making narratives.", "Rule 201: reference register."),
    ("handoff", "Next batch may consolidate the Rule 201 sound heads in a different proven construction or move to a fresh bounded field; sound-event and source traps remain closed.", "Rule 201: next cadence."),
]

LEXEMES = [
    ("kawal", "noun", None, "NA", "cooee; shout", "batch-243: sound-reference target only; no shouting event or source person."),
    ("ngawungkal", "noun", None, "NA", "halloo; shout from far away", "batch-243: sound-reference target only; no source-person event."),
    ("ngulnkul", "noun", None, "NA", "hum; voice without words", "batch-243: sound-reference target only; no humming/tune-making event."),
    ("nyinja", "noun", None, "NA", "grunt", "batch-243: sound-reference target only; no animal/source event."),
    ("wungka", "noun", None, "NA", "wail; scream", "batch-243: wail target only; no distress narrative or source person."),
    ("kandarr", "noun", None, "NA", "belch; burp", "batch-243: body-sound target only; no body-state source event."),
    ("ngangkun", "noun", None, "NA", "hiccups; hiccoughs", "batch-243: body-sound target only; no illness/diagnosis."),
    ("wankun", "noun", None, "NA", "hiccoughs", "batch-243: body-sound target only; no illness/diagnosis."),
    ("warimaji", "noun", None, "NA", "yawn", "batch-243: body-sound target only; no source-person event."),
    ("kunji", "noun", None, "NA", "sneeze", "batch-243: body-sound target only; no sickness/diagnosis."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-243: used in the hear/heard sense with bare sound-object nouns."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-243: bare pronoun A in hearing rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-243: bare pronoun A in hearing rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-243: bare pronoun A in past hearing rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-243: bare pronoun A in hearing rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-243: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-243: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; there", "batch-243: distal demonstrative support only; no new inflection."),
]


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-243-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 by SQL token estimate)",
        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 201 rows. Morphology checked target heads bare, pronoun A bare, support demonstratives uninflected, and nyaji-l tense forms. Lexicon checked ten audible-sound/body-sound senses and kept source persons/animals, previous sound heads, food/eating, illness, distress, mourning, body-part, tree, and event semantics closed. Syntax checked hearing/perception frames. Fidelity checked literal hear/heard English. Register stayed plain sound-reference.",
        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 previous sound-batch heads, sound-making verbs, source-person/animal rows, dog/pig/motor/food source, chewing/noisy-eating row, woman-in-distress narrative, mourning/death story, sickness/illness diagnosis, body-part possession, target case, compound, plural, derivation, productive reduplication, tree-reference, or demonstrative-inflection row.",
        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 201 lessons covering source checks, target senses, previous-head closures, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_243.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 201 sound targets, nyaji-l, pronouns, and demonstrative support heads.",
        artifact_path="batch_scripts/close_243.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 243: 50 accepted Rule 201 audible-sound reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_243.py",
        artifact_path="batch_scripts/close_243.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 LIKE 'batch-243%'").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, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_review_remaining}, verified corpus={verified}"
    )
    return 0


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