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

NOTES = (
    "LOW-FREQUENCY PROPERTY-ADJECTIVE LEXICAL EXPANSION AFTER RULE 204 (Rule 205). 50 rows. TARGETS: "
    "barrangkul flat, jalngka smooth/level, kurru-kurru crooked, darra narrow/too small, yalmbar wide, kiray quiet/slow, "
    "murru round, murru-murru lumpy, muru-muru close together, and manun-manun kind/merciful. FRAMES: NP ADJ, "
    "NP ADJ yaluy, NP ADJ yinyay, Yinya NP ADJ, and Yinya NP ADJ yinyay. REVIEW: target adjectives stayed bare; "
    "lexicalized hyphenated targets stayed dictionary headwords only; support nouns stayed in selected readings; "
    "yinya/yaluy/yinyay stayed uninflected support only. No negation, privative -kari, degree/comparison, target case, "
    "target compound, target plural, derivation, productive reduplication, perception verb, event/action, source/use, "
    "food/eating/cooking, repair, travel, ownership, illness/body-state, money/coin, or homograph-drift row was opened."
)

LESSONS = [
    ("process", "Rule 205 returned to lexical expansion after the Rule 204 construction consolidation.", "Rule 205: lexical cadence."),
    ("process", "A duplicate preflight caught Baral darra from Batch 145 and the row was recomposed to Kambi darra before banking.", "Rule 205: duplicate correction."),
    ("source", "Patz 3.1 supports adjectives as properties of nominal referents.", "Rule 205: adjective source."),
    ("source", "Patz example 2 supports bare NP ADJ property predicates.", "Rule 205: predicate source."),
    ("source", "Patz example 295 supports Yinya NP ADJ predicates.", "Rule 205: yinya source."),
    ("source", "Rules 238, 245, and 246 support yaluy/yinyay in property-predicate frames.", "Rule 205: deictic source."),
    ("lexicon", "Barrangkul stayed flat property only.", "Rule 205: barrangkul."),
    ("lexicon", "Jalngka stayed smooth/level adjective only; itchy-feeling noun homonym stayed closed.", "Rule 205: jalngka."),
    ("lexicon", "Kurru-kurru stayed physical crooked property only; wrong/abstract drift stayed closed.", "Rule 205: kurru-kurru."),
    ("lexicon", "Darra stayed narrow/too-small property only, with no degree bajaku.", "Rule 205: darra."),
    ("lexicon", "Yalmbar stayed wide property only.", "Rule 205: yalmbar."),
    ("lexicon", "Kiray stayed quiet person property only; slow-motion and secrecy adverb readings stayed closed.", "Rule 205: kiray."),
    ("lexicon", "Murru stayed round property only.", "Rule 205: murru."),
    ("lexicon", "Murru-murru stayed lexicalized lumpy adjective only.", "Rule 205: murru-murru."),
    ("lexicon", "Muru-muru stayed lexicalized close-together adjective only.", "Rule 205: muru-muru."),
    ("lexicon", "Manun-manun stayed kind/merciful character property only; no social-event row was opened.", "Rule 205: manun-manun."),
    ("lexicon", "Bubu stayed ground only; country/ownership reading stayed closed.", "Rule 205: bubu support."),
    ("lexicon", "Juku stayed wood only; tree-use/source/action readings stayed closed.", "Rule 205: juku support."),
    ("lexicon", "Baral stayed road/path noun only; feel/perception verb homograph stayed closed.", "Rule 205: baral support."),
    ("lexicon", "Kambi stayed clothing only; flying-fox homograph stayed closed.", "Rule 205: kambi support."),
    ("lexicon", "Kulji stayed pebble/stone only; money/coin secondary sense stayed closed.", "Rule 205: kulji support."),
    ("lexicon", "Bama stayed person/people only; no kin/social-event row was opened.", "Rule 205: bama support."),
    ("morphology", "All target adjectives stayed bare: no case, privative, degree, comparison, inchoative, causative, plural, compound, or derivation.", "Rule 205: bare targets."),
    ("morphology", "Lexicalized hyphenated headwords kurru-kurru, murru-murru, muru-muru, and manun-manun were not treated as productive reduplication.", "Rule 205: lexicalized reduplication."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected support heads.", "Rule 205: support morphology."),
    ("syntax", "Rows 1-10 used NP ADJ.", "Rule 205: NP property frame."),
    ("syntax", "Rows 11-20 used NP ADJ yaluy.", "Rule 205: here property frame."),
    ("syntax", "Rows 21-30 used NP ADJ yinyay.", "Rule 205: there property frame."),
    ("syntax", "Rows 31-40 used Yinya NP ADJ.", "Rule 205: demonstrative property frame."),
    ("syntax", "Rows 41-50 used Yinya NP ADJ yinyay.", "Rule 205: demonstrative there-property frame."),
    ("fidelity", "English stayed literal: subject noun plus selected adjective and optional here/there/that support.", "Rule 205: literal English."),
    ("fidelity", "No English negation, degree, comparison, motion, secrecy, eating, cooking, repair, travel, ownership, source/use, illness, body-state, or perception wording was imported.", "Rule 205: denied English fields."),
    ("register", "Rows remained plain property descriptions, not narratives, social events, repairs, travel reports, food events, or perception reports.", "Rule 205: property register."),
    ("handoff", "Next batch may consolidate Rule 205 adjectives in a sourced construction or run a targeted debt sweep; do not infer negation, degree, event, source/use, or homograph semantics from Rule 205.", "Rule 205: next cadence."),
]

LEXEMES = [
    ("barrangkul", "adjective", None, "NA", "flat", "batch-247: flat property adjective only."),
    ("jalngka", "adjective", None, "NA", "smooth; level", "batch-247: smooth/level adjective only; itchy-feeling noun homonym closed."),
    ("kurru-kurru", "adjective", None, "NA", "crooked; wrong", "batch-247: physical crooked property only; no abstract wrong/event row."),
    ("darra", "adjective", None, "NA", "narrow; too small", "batch-247: narrow/too-small property only; no degree bajaku."),
    ("yalmbar", "adjective", None, "NA", "wide", "batch-247: wide property only."),
    ("kiray", "adjective", None, "NA", "slow; quiet", "batch-247: quiet person property only; no motion or secrecy adverb."),
    ("murru", "adjective", None, "NA", "round", "batch-247: round property only."),
    ("murru-murru", "adjective", None, "NA", "lumpy", "batch-247: lexicalized dictionary adjective only; no productive reduplication."),
    ("muru-muru", "adjective", None, "NA", "close together", "batch-247: lexicalized dictionary adjective only; no productive reduplication."),
    ("manun-manun", "adjective", None, "NA", "kind; merciful", "batch-247: character property only; no social-event row."),
    ("bubu", "noun", None, "NA", "ground; earth", "batch-247: support subject as ground only; country/ownership closed."),
    ("juku", "noun", None, "NA", "tree; wood; stick", "batch-247: support subject as wood only; use/source/action closed."),
    ("baral", "noun", None, "NA", "road; path; track", "batch-247: support subject as road/path only; feel/perception verb closed."),
    ("kambi", "noun", None, "NA", "clothing; flying fox", "batch-247: support subject as clothing only; flying-fox homograph closed."),
    ("kulji", "noun", None, "NA", "pebble; small stone", "batch-247: support subject as pebble/stone only; money/coin reading closed."),
    ("bama", "noun", None, "NA", "person; people", "batch-247: support subject as person/people only; no social-event row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-247: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-247: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those; there", "batch-247: 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-247-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 205 rows. Morphology checked bare targets, no negation, no -kari, no degree, no case, lexicalized hyphenated targets only, and yinya/yaluy/yinyay uninflected. Lexicon checked selected target senses and support noun readings. Syntax checked five property frame bands. 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 negation, privative -kari, perception verb, baral feel/perception verb, degree/comparison, target case/compound/plural/derivation, productive reduplication, motion/travel, secrecy adverb, food/eating/cooking, repair, ownership, source/use, illness/body-state, money/coin, itchy-feeling homonym, social-event, yala/yanyu, or support inflection.",
        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 205 lessons covering source checks, target senses, support noun readings, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_247.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 205 targets, support nouns, and demonstrative heads.",
        artifact_path="batch_scripts/close_247.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 247: 50 accepted Rule 205 low-frequency property-adjective lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_247.py",
        artifact_path="batch_scripts/close_247.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]
    lessons = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (batch_id,)).fetchone()[0]
    lexeme_logs = db.execute("SELECT COUNT(*) FROM lexeme_log WHERE action='batch-247-verify'").fetchone()[0]
    process_events = db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (LABEL,)).fetchone()[0]
    under_after = db.execute("SELECT COUNT(*) FROM sentences WHERE status='under_review'").fetchone()[0]
    verified_after = db.execute("SELECT COUNT(*) FROM sentences WHERE status IN ('accepted','revised')").fetchone()[0]
    print(
        f"closed {LABEL}: 50 accepted rows, {reviews} review passes, {lessons} lessons, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_after}, verified corpus={verified_after}"
    )
    return 0


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