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

NOTES = (
    "HUMAN/KIN REFERENCE LEXICAL EXPANSION AFTER RULE 156 (Rule 157). 50 rows. TARGETS: bama person, "
    "dingkar man, jalbu woman, karrkay child, ngamu mother, nganjan father, jawun friend, dunyu husband, "
    "warru young man, wulman old man. FRAMES: bare deictic identification with yinyay, present perception with "
    "ngayu/yundu, past perception with jana, and yaluy-supported present perception with ngana. REVIEW: all targets "
    "stayed bare; no target case forms, compounds, possessives, comitatives, kin plurals, address forms, marriage/"
    "change-of-state, avoidance, travel, food, conflict, work, teaching, asking, or social-event semantics."
)

LESSONS = [
    ("process", "A human/kin lexical pass can safely grow participant vocabulary by using deictic and perception frames before opening social-event syntax.", "Rule 157: lexical before social events."),
    ("process", "Rule 157 admitted ten human/kin targets and kept all target heads bare.", "Rule 157: target inventory."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 157: duplicate preflight."),
    ("lexicon", "`bama` was admitted as person/people only; no crowd, ethnicity, land, teaching, or event row.", "Rule 157: bama lexical scope."),
    ("lexicon", "`dingkar` was admitted as man only; no male-classifier, possessor, or agent-action row.", "Rule 157: dingkar lexical scope."),
    ("lexicon", "`jalbu` was admitted as woman only; no female-classifier, pair/plural, or action row.", "Rule 157: jalbu lexical scope."),
    ("lexicon", "`karrkay` was admitted as child only; the adjective 'small' sense stayed closed.", "Rule 157: karrkay noun-only."),
    ("lexicon", "`ngamu` was admitted as mother only; place-name and compound senses stayed closed.", "Rule 157: ngamu mother-only."),
    ("lexicon", "`nganjan` was admitted as father only; dyadic and possessive frames stayed closed.", "Rule 157: nganjan father-only."),
    ("lexicon", "`jawun` was admitted as friend only; relation/KPL/comitative frames stayed closed.", "Rule 157: jawun friend-only."),
    ("lexicon", "`dunyu` was admitted as husband only; marriage/inchoative frames stayed closed.", "Rule 157: dunyu husband-only."),
    ("lexicon", "`warru` was admitted as young man only; plural, age-adverbial, and action frames stayed closed.", "Rule 157: warru young-man-only."),
    ("lexicon", "`wulman` was admitted as old man only; husband and old-animal senses stayed closed.", "Rule 157: wulman old-man-only."),
    ("morphology", "All human/kin target heads stayed bare; no target LOC, DAT, ABL, ERG, INST, COMIT, POSS, KPL, pair, reduplicated, or compound morphology appeared.", "Rule 157: target case restraint."),
    ("morphology", "`yinyay` and `yaluy` were support deictics only and were not attached to target heads.", "Rule 157: deictic support restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 157: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 157: perception tense forms."),
    ("syntax", "Bare deictic rows used one human/kin target plus `yinyay` and no predicator.", "Rule 157: deictic syntax."),
    ("syntax", "Present perception rows used one bare human/kin object plus `nyajil`.", "Rule 157: present perception syntax."),
    ("syntax", "Past perception rows used one bare human/kin object plus `nyajin`.", "Rule 157: past perception syntax."),
    ("syntax", "`yaluy`-supported present perception rows used one bare target, one support deictic, and `nyajil`.", "Rule 157: yaluy-supported perception syntax."),
    ("fidelity", "English labels selected only source-attested human/kin senses and did not add action, possession, marriage, avoidance, address, or social-event inference.", "Rule 157: selected-sense fidelity."),
    ("fidelity", "No Patz example-event content was imported as a sentence claim.", "Rule 157: no source-event import."),
    ("register", "Rows remained ordinary reference/perception statements, not genealogical, ceremonial, institutional, or narrative-event claims.", "Rule 157: register scope."),
    ("handoff", "Next cadence should consolidate these human/kin heads before opening possession, plural, comitative, address, or social-event frames.", "Rule 157: next cadence."),
    ("handoff", "Carry forward human/kin traps: keep kinship plural, possessive, address, marriage, asking, teaching, food, conflict, travel, and work semantics closed unless deliberately sourced.", "Rule 157: carry-forward traps."),
]

LEXEMES = [
    ("bama", "noun", None, "NA", "person; people", "batch-199: sourced from dictionary/Patz and admitted as person/people only; no crowd/ethnicity/teaching/event row."),
    ("dingkar", "noun", None, "NA", "man", "batch-199: retained man only; no male-classifier, possessor, or agent-action row."),
    ("jalbu", "noun", None, "NA", "woman", "batch-199: retained woman only; no pair/plural or action row."),
    ("karrkay", "noun", None, "NA", "child", "batch-199: selected child noun sense only; adjective small stayed closed."),
    ("ngamu", "noun", None, "NA", "mother", "batch-199: retained mother only; place-name and compound senses closed."),
    ("nganjan", "noun", None, "NA", "father", "batch-199: retained father only; dyadic and possessive frames closed."),
    ("jawun", "noun", None, "NA", "friend", "batch-199: selected friend sense only; relation/KPL/comitative frames closed."),
    ("dunyu", "noun", None, "NA", "husband", "batch-199: retained husband only; marriage/inchoative frames closed."),
    ("warru", "noun", None, "NA", "young man", "batch-199: retained young man only; plural/age-adverbial/action frames closed."),
    ("wulman", "noun", None, "NA", "old man", "batch-199: selected old man only; husband and old-animal senses closed."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-199: retained local demonstrative in deictic identification rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-199: retained local demonstrative in supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-199: retained past and nonpast perception rows with human/kin objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-199: bare pronoun A in perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-199: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-199: bare pronoun A in past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-199: bare pronoun A in perception rows."),
]


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-199-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)",
                 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 157 rows. Morphology checked bare human/kin targets, no target case/compound/possessive/comitative/KPL/pair/reduplication forms, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected human/kin senses and closed bama crowd/event, karrkay adjective, jawun relation/KPL, wulman husband/old-animal, and kinship-event traps. Syntax checked deictic identification, present perception, past perception, and yaluy-supported perception. Fidelity checked no social-event import. Register stayed ordinary.",
                 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 target locative/dative/ablative/ergative/instrument/comitative/possessive/compound/KPL/pair/reduplicated form, no marriage/change-of-state, no asking/teaching/talking, no food, conflict, hunting, travel, work, possession, avoidance, address, or ceremonial/social-event semantics.",
                 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 157 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_199.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 157 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_199.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 199: 50 accepted Rule 157 human/kin reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_199.py", artifact_path="batch_scripts/close_199.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 detail LIKE '%batch-199:%'").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, {lexeme_logs} lexeme/source-log rows, {process_events} process events, under_review={under_review_remaining}, verified corpus={verified}")
    return 0


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