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

NOTES = (
    "EXTENDED-KIN REFERENCE LEXICAL EXPANSION AFTER RULE 158 (Rule 159). 50 rows. TARGETS: babi grandmother, "
    "kami grandfather, kalnga mother's brother, bimakay father's sister, ngaji mother's father, jija son's-child "
    "grandchild, kaminjarr daughter's-child grandchild, kangkal own child, yaba older brother, and babarr older "
    "sister. 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, pair/reduplication, address forms, marriage/change-of-state, "
    "avoidance, travel, food, conflict, work, teaching, asking, or social-event semantics."
)

LESSONS = [
    ("process", "Rule 159 extends kin/person reference only after Rule 158 construction consolidation, keeping the same low-risk deictic/perception frames.", "Rule 159: lexical after construction pass."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 159: duplicate preflight."),
    ("lexicon", "`babi` was admitted as grandmother only; no possessive-house, address, or narrative event row.", "Rule 159: babi lexical scope."),
    ("lexicon", "`kami` was admitted as grandfather only; no possessive, location, or property row.", "Rule 159: kami lexical scope."),
    ("lexicon", "`kalnga` was admitted as mother's brother only; no possessor, authority, teaching, or first-spear event row.", "Rule 159: kalnga lexical scope."),
    ("lexicon", "`bimakay` was admitted as father's sister only; no possessive, address, or social-event row.", "Rule 159: bimakay lexical scope."),
    ("lexicon", "`ngaji` was admitted as mother's father only; no death, season, possessive, or narrative row.", "Rule 159: ngaji lexical scope."),
    ("lexicon", "`jija` was admitted as son's-child grandchild only; no possession or plural frame.", "Rule 159: jija lexical scope."),
    ("lexicon", "`kaminjarr` was admitted as daughter's-child grandchild only; no many-grandchildren or gendered-grandchild row.", "Rule 159: kaminjarr lexical scope."),
    ("lexicon", "`kangkal` was admitted as own child / son-or-daughter only; possessive, reduplicated, privative, pair, and plural frames stayed closed.", "Rule 159: kangkal lexical scope."),
    ("lexicon", "`yaba` was admitted as older brother only; eel and fish senses stayed closed.", "Rule 159: yaba homograph."),
    ("lexicon", "`babarr` was admitted as older sister only; young-cassowary sense stayed closed.", "Rule 159: babarr homograph."),
    ("morphology", "All extended-kin target heads stayed bare; no target LOC, DAT, ABL, ERG, INST, COMIT, POSS, KPL, pair, reduplicated, or compound morphology appeared.", "Rule 159: target case restraint."),
    ("morphology", "`yinyay` and `yaluy` were support deictics only and were not attached to target heads.", "Rule 159: deictic support restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 159: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 159: perception tense forms."),
    ("syntax", "Bare deictic rows used one extended-kin target plus `yinyay` and no predicator.", "Rule 159: deictic syntax."),
    ("syntax", "Present perception rows used one bare extended-kin object plus `nyajil`.", "Rule 159: present perception syntax."),
    ("syntax", "Past perception rows used one bare extended-kin object plus `nyajin`.", "Rule 159: past perception syntax."),
    ("syntax", "`yaluy`-supported present perception rows used one bare target, one support deictic, and `nyajil`.", "Rule 159: yaluy-supported perception syntax."),
    ("fidelity", "English labels selected only source-attested kin senses and did not add action, possession, marriage, avoidance, address, or social-event inference.", "Rule 159: selected-sense fidelity."),
    ("fidelity", "No Patz example-event content was imported as a sentence claim.", "Rule 159: no source-event import."),
    ("register", "Rows remained ordinary reference/perception statements, not genealogical, ceremonial, institutional, or narrative-event claims.", "Rule 159: register scope."),
    ("handoff", "Next cadence should consolidate these extended-kin heads before opening possession, plural, comitative, address, or social-event frames.", "Rule 159: next cadence."),
    ("handoff", "Carry forward extended-kin traps: keep kinship plural, possessive, address, marriage, asking, teaching, food, conflict, travel, work, homograph animal senses, and avoidance semantics closed unless deliberately sourced.", "Rule 159: carry-forward traps."),
]

LEXEMES = [
    ("babi", "noun", None, "NA", "grandmother", "batch-201: admitted grandmother only; no possessive-house, address, or narrative event row."),
    ("kami", "noun", None, "NA", "grandfather", "batch-201: admitted grandfather only; no possessive, location, or property row."),
    ("kalnga", "noun", None, "NA", "mother's brother", "batch-201: admitted mother's brother only; no authority/teaching/event row."),
    ("bimakay", "noun", None, "NA", "father's sister", "batch-201: admitted father's sister only; no possessive or address row."),
    ("ngaji", "noun", None, "NA", "mother's father", "batch-201: admitted mother's father only; no death/season/narrative row."),
    ("jija", "noun", None, "NA", "son's child; grandchild", "batch-201: admitted son's-child grandchild only; no plural or possession row."),
    ("kaminjarr", "noun", None, "NA", "daughter's child; grandchild", "batch-201: admitted daughter's-child grandchild only; no plural or possession row."),
    ("kangkal", "noun", None, "NA", "own child; son or daughter", "batch-201: admitted own-child sense only; no reduplication, possessive, pair, or privative row."),
    ("yaba", "noun", None, "NA", "older brother", "batch-201: admitted older-brother sense only; eel homograph stayed closed."),
    ("babarr", "noun", None, "NA", "older sister", "batch-201: admitted older-sister sense only; young-cassowary homograph stayed closed."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-201: retained local demonstrative in deictic identification rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-201: retained local demonstrative in supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-201: retained past and nonpast perception rows with extended-kin objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-201: bare pronoun A in perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-201: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-201: bare pronoun A in past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-201: bare pronoun A in yaluy-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-201-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 159 rows. Morphology checked bare extended-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 extended-kin senses and closed yaba eel, babarr cassowary, kangkal possessive/reduplicated, 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 159 lessons covering process, lexical senses, homographs, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_201.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 159 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_201.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 201: 50 accepted Rule 159 extended-kin reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_201.py", artifact_path="batch_scripts/close_201.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-201:%'").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())
