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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 159 (Rule 160). 50 rows. RETAINED 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 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, homograph animal senses, or social-event semantics."
)

LESSONS = [
    ("process", "A construction consolidation pass can safely reuse the Rule 159 extended-kin field without adding new lexemes or social-event meaning.", "Rule 160: construction after lexical pass."),
    ("process", "Rule 160 retained the ten Rule 159 extended-kin heads and added no new target head.", "Rule 160: retained inventory."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 160: duplicate preflight."),
    ("lexicon", "`babi` stayed grandmother only; no possessive-house, address, or narrative row.", "Rule 160: babi carry-forward."),
    ("lexicon", "`kami` stayed grandfather only; no possessive, location, or property row.", "Rule 160: kami carry-forward."),
    ("lexicon", "`kalnga` stayed mother's brother only; no possessor, authority, teaching, or first-spear event row.", "Rule 160: kalnga carry-forward."),
    ("lexicon", "`bimakay` stayed father's sister only; no possessive, address, or social-event row.", "Rule 160: bimakay carry-forward."),
    ("lexicon", "`ngaji` stayed mother's father only; no death, season, possessive, or narrative row.", "Rule 160: ngaji carry-forward."),
    ("lexicon", "`jija` stayed son's-child grandchild only; no possession or plural frame.", "Rule 160: jija carry-forward."),
    ("lexicon", "`kaminjarr` stayed daughter's-child grandchild only; no many-grandchildren or gendered-grandchild row.", "Rule 160: kaminjarr carry-forward."),
    ("lexicon", "`kangkal` stayed own child / son-or-daughter only; possessive, reduplicated, privative, pair, and plural frames stayed closed.", "Rule 160: kangkal carry-forward."),
    ("lexicon", "`yaba` stayed older brother only; eel and fish senses stayed closed.", "Rule 160: yaba homograph."),
    ("lexicon", "`babarr` stayed older sister only; young-cassowary sense stayed closed.", "Rule 160: 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 160: target case restraint."),
    ("morphology", "`yinyay` and `yaluy` remained support deictics only and were not attached to target heads.", "Rule 160: deictic support restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 160: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 160: perception tense forms."),
    ("syntax", "Bare deictic rows used one extended-kin target plus `yaluy` and no predicator.", "Rule 160: yaluy deictic syntax."),
    ("syntax", "`yinyay`-supported present perception rows used one bare extended-kin object plus `nyajil`.", "Rule 160: yinyay-supported perception."),
    ("syntax", "`yaluy`-supported present and past perception rows used one bare target, one support deictic, and `nyaji-l`.", "Rule 160: yaluy-supported perception."),
    ("fidelity", "English labels selected only source-attested kin senses and did not add action, possession, marriage, avoidance, address, or social-event inference.", "Rule 160: selected-sense fidelity."),
    ("fidelity", "The English here/there contrast follows `yaluy`/`yinyay` and does not add location-case morphology.", "Rule 160: deictic fidelity."),
    ("register", "Rows remained ordinary reference/perception statements, not genealogical, ceremonial, institutional, or narrative-event claims.", "Rule 160: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but keep extended-kin possession, plural, comitative, address, and social-event frames closed unless deliberately sourced.", "Rule 160: next cadence."),
    ("handoff", "Carry forward extended-kin traps: kinship plural, possessive, address, marriage, asking, teaching, food, conflict, travel, work, homograph animal senses, and avoidance semantics remain closed.", "Rule 160: carry-forward traps."),
]

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