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

NOTES = (
    "SURFACE-PROPERTY ADJECTIVE LEXICAL EXPANSION AFTER RULE 202 (Rule 203). 50 rows. TARGETS: mulun folded/closed, "
    "dangal baggy/sloppy, dulngki wide, dungkul huge/enormous, dunju-dunju coarse/knobbed, jala-jala loose, "
    "jalkar-jalkar steep, yuku thick, muja-muja rotten/decayed, and nguyal sticky. FRAMES: NP ADJ, NP ADJ yaluy, "
    "NP ADJ yinyay, Yinya NP ADJ, and Yinya NP ADJ yinyay. REVIEW: all target adjectives stayed bare; lexicalized "
    "reduplicated targets were admitted only as dictionary headwords; support nouns stayed in selected readings; "
    "yinya/yaluy/yinyay stayed uninflected support only. No perception verb, negation, -kari, degree/comparison, "
    "inchoative, causative, action/event, use/source, illness/body-state, food/eating/cooking, clothing wear/make, "
    "road travel, house repair, wood cutting/use, proximal yala/yanyu, target case, target compound, target plural, or "
    "productive reduplication row was opened."
)

LESSONS = [
    ("process", "Rule 203 returned to lexical expansion after the Rule 201-202 sound-reference pair.", "Rule 203: lexical cadence."),
    ("process", "The selected field was surface/physical-property adjectives, not actions or uses.", "Rule 203: property scope."),
    ("process", "Exact duplicate preflight over all 50 planned surface-property adjective surfaces returned no cross-corpus accepted/revised/under_review collisions.", "Rule 203: duplicate preflight."),
    ("source", "Patz 3.1 supports adjectives as nominals denoting properties, including dimension, physical characteristics, texture, colour, and taste.", "Rule 203: adjective-class source."),
    ("source", "Patz example 2 supports bare NP ADJ predicates such as Kirrbaji yalbay.", "Rule 203: bare property predicate source."),
    ("source", "Patz example 295 supports Yinya NP ADJ predicates through Yinya mayi ngulkurr.", "Rule 203: yinya property predicate source."),
    ("source", "Patz 3.7 supports yinya, yaluy, and yinyay as demonstrative/local support forms.", "Rule 203: deictic source."),
    ("lexicon", "Mulun was admitted only as folded/closed, with kambi as clothing; no clothing folding/opening/closing event.", "Rule 203: mulun folded only."),
    ("lexicon", "Dangal was admitted only as baggy/sloppy, with kambi as clothing; no wearing/making event.", "Rule 203: dangal baggy only."),
    ("lexicon", "Dulngki was admitted only as wide, with baral as road/path noun; baral feel/perception verb stayed closed.", "Rule 203: dulngki wide only."),
    ("lexicon", "Dungkul was admitted only as huge/enormous, with bayan as house/camp; no ownership or repair row.", "Rule 203: dungkul huge only."),
    ("lexicon", "Dunju-dunju was admitted only as the dictionary-listed coarse/knobbed adjective; no productive reduplication was inferred.", "Rule 203: dunju-dunju lexicalized only."),
    ("lexicon", "Jala-jala was admitted only as the dictionary-listed loose adjective; no productive reduplication was inferred.", "Rule 203: jala-jala lexicalized only."),
    ("lexicon", "Jalkar-jalkar was admitted only as the dictionary-listed steep adjective; no road/travel event was opened.", "Rule 203: jalkar-jalkar steep only."),
    ("lexicon", "Yuku was admitted only as thick, with juku as wood; no generic big-field expansion or wood-use row.", "Rule 203: yuku thick only."),
    ("lexicon", "Muja-muja was admitted only as rotten/decayed, especially with juku wood; no cutting/use/source claim was opened.", "Rule 203: muja-muja rotten only."),
    ("lexicon", "Nguyal was admitted only as sticky, with mayi food as subject; no honey, eating, cooking, or gathering row was opened.", "Rule 203: nguyal sticky only."),
    ("lexicon", "Support noun kambi stayed clothing only in this batch; flying-fox homograph stayed closed.", "Rule 203: kambi support reading."),
    ("lexicon", "Support noun baral stayed road/path only in this batch; feel/perception verb homograph stayed closed.", "Rule 203: baral support reading."),
    ("lexicon", "Support nouns bubu, bayan, juku, and mayi stayed subject nouns only; country/ownership, repair, cutting/use, food-source, eating, and cooking readings stayed closed.", "Rule 203: support noun restraint."),
    ("morphology", "All target adjectives stayed bare: no target case, privative, degree, comparison, inchoative, causative, plural, compound, or productive reduplication.", "Rule 203: bare target morphology."),
    ("morphology", "Lexicalized hyphenated/reduplicated dictionary headwords dunju-dunju, jala-jala, jalkar-jalkar, and muja-muja were not treated as productive morphology.", "Rule 203: lexicalized reduplication."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads.", "Rule 203: support morphology restraint."),
    ("syntax", "Rows 1-10 used bare NP ADJ predicates.", "Rule 203: NP ADJ frame."),
    ("syntax", "Rows 11-20 used NP ADJ yaluy.", "Rule 203: here property frame."),
    ("syntax", "Rows 21-30 used NP ADJ yinyay.", "Rule 203: there property frame."),
    ("syntax", "Rows 31-40 used Yinya NP ADJ.", "Rule 203: demonstrative property frame."),
    ("syntax", "Rows 41-50 used Yinya NP ADJ yinyay.", "Rule 203: demonstrative there-property frame."),
    ("fidelity", "English stayed literal: subject noun plus selected adjective and optional here/there/that support.", "Rule 203: literal English."),
    ("fidelity", "No English action, cause, repair, wearing, making, travel, cooking, eating, illness, body-state, source, comparison, degree, negation, or perception wording was imported.", "Rule 203: denied English fields."),
    ("register", "Rows remained plain property descriptions of ordinary objects and surfaces, not narratives or event reports.", "Rule 203: property register."),
    ("handoff", "Next batch may consolidate these Rule 203 adjectives in perception or negation only if those constructions are freshly sourced; otherwise return to a new bounded lexical field.", "Rule 203: next cadence."),
]

LEXEMES = [
    ("mulun", "adjective", None, "NA", "folded; closed", "batch-245: property adjective target only; no folding/opening/closing event."),
    ("dangal", "adjective", None, "NA", "baggy; sloppy", "batch-245: property adjective target only; no clothing wear/make event."),
    ("dulngki", "adjective", None, "NA", "wide", "batch-245: property adjective target only; no road/travel event."),
    ("dungkul", "adjective", None, "NA", "huge; enormous", "batch-245: property adjective target only; no house/ownership row."),
    ("dunju-dunju", "adjective", None, "NA", "coarse; knobbed; spiky", "batch-245: lexicalized dictionary adjective only; no productive reduplication."),
    ("jala-jala", "adjective", None, "NA", "loose; loosely put together", "batch-245: lexicalized dictionary adjective only; no productive reduplication or clothing event."),
    ("jalkar-jalkar", "adjective", None, "NA", "steep", "batch-245: lexicalized dictionary adjective only; no road/travel event."),
    ("yuku", "adjective", None, "NA", "big; thick", "batch-245: property adjective target selected as thick only; no generic big-field expansion."),
    ("muja-muja", "adjective", None, "NA", "rotten; decayed; easily broken", "batch-245: lexicalized dictionary adjective only; no wood cutting/use/source row."),
    ("nguyal", "adjective", None, "NA", "sticky", "batch-245: property adjective target only; no honey/eating/cooking row."),
    ("bubu", "noun", None, "NA", "ground; earth; country", "batch-245: support subject noun as ground only; no country/ownership claim."),
    ("kambi", "noun", None, "NA", "clothing; flying fox", "batch-245: support subject noun as clothing only; flying-fox homograph closed."),
    ("baral", "noun", None, "NA", "road; path; track", "batch-245: support subject noun as road/path only; feel/perception verb homograph closed."),
    ("bayan", "noun", None, "NA", "house; camp; shelter", "batch-245: support subject noun only; no repair or ownership row."),
    ("juku", "noun", None, "NA", "tree; wood; stick", "batch-245: support subject noun as wood only; no cutting/use/source row."),
    ("mayi", "noun", None, "NA", "food; plant food; fruit", "batch-245: support subject noun as food only; no eating/cooking/gathering row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-245: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-245: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those; there", "batch-245: 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-245-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 203 rows. Morphology checked target adjectives bare, lexicalized hyphenated targets treated only as dictionary headwords, yinya/yaluy/yinyay uninflected, and no negation/degree/case morphology. Lexicon checked ten surface-property adjective senses plus support noun readings. Syntax checked five NP/property frames. Fidelity checked literal property English. Register stayed plain property description.",
        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 perception verb, nyaji-l, baral feel/perception verb, negation, -kari, degree/comparison, inchoative, causative, action/event, use/source claim, illness/body-state reading, food/eating/cooking row, clothing wear/make row, road travel row, house repair row, wood cutting/use row, proximal yala/yanyu, target case, target compound, target plural, or productive reduplication 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 203 lessons covering source checks, target senses, support noun readings, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_245.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 203 target adjectives, support nouns, and demonstrative heads.",
        artifact_path="batch_scripts/close_245.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 245: 50 accepted Rule 203 surface-property adjective lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_245.py",
        artifact_path="batch_scripts/close_245.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-245%'").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())
