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

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

LESSONS = [
    ("process", "A construction consolidation pass can safely reuse a lexical field without adding new lexemes or social-event meaning.", "Rule 158: construction after lexical pass."),
    ("process", "Rule 158 retained the ten Rule 157 human/kin heads and added no new target head.", "Rule 158: retained inventory."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 158: duplicate preflight."),
    ("lexicon", "`bama` stayed person/people only; no crowd, ethnicity, teaching, or event row.", "Rule 158: bama carry-forward."),
    ("lexicon", "`dingkar` stayed man only; no male-classifier, possessor, or agent-action row.", "Rule 158: dingkar carry-forward."),
    ("lexicon", "`jalbu` stayed woman only; no pair/plural, possessor, or action row.", "Rule 158: jalbu carry-forward."),
    ("lexicon", "`karrkay` stayed child only; the adjective 'small' sense stayed closed.", "Rule 158: karrkay carry-forward."),
    ("lexicon", "`ngamu` stayed mother only; place-name and compound senses stayed closed.", "Rule 158: ngamu carry-forward."),
    ("lexicon", "`nganjan` stayed father only; dyadic, possessive, and social-event frames stayed closed.", "Rule 158: nganjan carry-forward."),
    ("lexicon", "`jawun` stayed friend only; relation/KPL/comitative frames stayed closed.", "Rule 158: jawun carry-forward."),
    ("lexicon", "`dunyu` stayed husband only; marriage/inchoative frames stayed closed.", "Rule 158: dunyu carry-forward."),
    ("lexicon", "`warru` stayed young man only; plural, age-adverbial, and action frames stayed closed.", "Rule 158: warru carry-forward."),
    ("lexicon", "`wulman` stayed old man only; husband and old-animal senses stayed closed.", "Rule 158: wulman carry-forward."),
    ("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 158: target case restraint."),
    ("morphology", "`yinyay` and `yaluy` remained support deictics only and were not attached to target heads.", "Rule 158: deictic support restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 158: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 158: perception tense forms."),
    ("syntax", "Bare deictic rows used one human/kin target plus `yaluy` and no predicator.", "Rule 158: yaluy deictic syntax."),
    ("syntax", "`yinyay`-supported present perception rows used one bare human/kin object plus `nyajil`.", "Rule 158: yinyay-supported perception."),
    ("syntax", "`yaluy`-supported present and past perception rows used one bare target, one support deictic, and `nyaji-l`.", "Rule 158: yaluy-supported perception."),
    ("fidelity", "English labels selected only source-attested human/kin senses and did not add action, possession, marriage, avoidance, address, or social-event inference.", "Rule 158: selected-sense fidelity."),
    ("fidelity", "The English here/there contrast follows `yaluy`/`yinyay` and does not add location-case morphology.", "Rule 158: deictic fidelity."),
    ("register", "Rows remained ordinary reference/perception statements, not genealogical, ceremonial, institutional, or narrative-event claims.", "Rule 158: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but keep human/kin possession, plural, comitative, address, and social-event frames closed unless deliberately sourced.", "Rule 158: next cadence."),
    ("handoff", "Carry forward human/kin traps: kinship plural, possessive, address, marriage, asking, teaching, food, conflict, travel, work, and avoidance semantics remain closed.", "Rule 158: carry-forward traps."),
]

LEXEMES = [
    ("bama", "noun", None, "NA", "person; people", "batch-200: retained person/people only in deictic/perception construction consolidation."),
    ("dingkar", "noun", None, "NA", "man", "batch-200: retained man only; no male-classifier, possessor, or agent-action row."),
    ("jalbu", "noun", None, "NA", "woman", "batch-200: retained woman only; no pair/plural or action row."),
    ("karrkay", "noun", None, "NA", "child", "batch-200: retained child noun sense only; adjective small stayed closed."),
    ("ngamu", "noun", None, "NA", "mother", "batch-200: retained mother only; place-name and compound senses closed."),
    ("nganjan", "noun", None, "NA", "father", "batch-200: retained father only; dyadic and possessive frames closed."),
    ("jawun", "noun", None, "NA", "friend", "batch-200: retained friend sense only; relation/KPL/comitative frames closed."),
    ("dunyu", "noun", None, "NA", "husband", "batch-200: retained husband only; marriage/inchoative frames closed."),
    ("warru", "noun", None, "NA", "young man", "batch-200: retained young man only; plural/age-adverbial/action frames closed."),
    ("wulman", "noun", None, "NA", "old man", "batch-200: retained old man only; husband and old-animal senses closed."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-200: retained local demonstrative in supported perception rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-200: retained local demonstrative in deictic and supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-200: retained past and nonpast perception rows with human/kin objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-200: bare pronoun A in yinyay-supported perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-200: bare pronoun A in yaluy-supported perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-200: bare pronoun A in past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-200: bare pronoun A in yinyay-supported 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-200-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 158 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 kept bama crowd/event, karrkay adjective, jawun relation/KPL, wulman husband/old-animal, and kinship-event traps closed. Syntax checked bare yaluy deictic identification, yinyay-supported present perception, yaluy-supported present perception, and yaluy-supported past 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 158 lessons covering process, lexical carry-forward, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_200.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 retained Rule 158 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_200.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 200: 50 accepted Rule 158 human/kin construction-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_200.py", artifact_path="batch_scripts/close_200.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-200:%'").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())
