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

NOTES = (
    "VISUAL-PROPERTY PERCEPTION CONSTRUCTION CONSOLIDATION AFTER RULE 197 (Rule 198). 50 rows. TARGETS: "
    "ngumbu black/dark, bingaji light-coloured, ngala-ngala red, and dayirr clean/clear. OBJECT NOUNS: kulji "
    "stone, juku tree, ngurrban cloud, mungka hair, kambi clothing, nganka flower, karrambil king parrot, bana "
    "water, bubu ground, and bayan house. FRAMES: Ngayu NP ADJ nyajil, Yundu NP ADJ nyajil, Jana NP ADJ nyajin, "
    "Ngana NP ADJ yaluy nyajil, and Yundu NP ADJ yinyay nyajil. REVIEW: pronoun A stayed bare; object NPs stayed "
    "unmarked with noun before adjective; jana rows alone used past nyajin; ngana/yundu local rows kept yaluy/yinyay "
    "as support only. No negation, -kari, common-noun perceiver, ERG decision, hearing/listening English, colour-field "
    "expansion, case, degree, comparison, causative, inchoative, plural, compound, productive reduplication, weather, "
    "ownership, material-use, body-possession, or bird-event row was opened."
)

LESSONS = [
    ("process", "Rule 198 consolidated the Rule 197 visual-property field in perception frames rather than opening new colour lexemes.", "Rule 198: construction consolidation after lexical expansion."),
    ("process", "Negated colour/property rows were deliberately deferred because kari and -kari risk reopening white/pale drift.", "Rule 198: no kari in visual-property field."),
    ("process", "The batch used pronoun perceivers only, avoiding new common-noun ERG decisions.", "Rule 198: pronoun A only."),
    ("lexicon", "Ngumbu stayed black/dark only; no ngumbu-kari, white/pale, night, darkness-setting, or ngumbul drift was admitted.", "Rule 198: ngumbu perception discipline."),
    ("lexicon", "Bingaji stayed light-coloured adjective only; no white-haired-person noun reading was admitted.", "Rule 198: bingaji adjective only."),
    ("lexicon", "Ngala-ngala stayed red/reddish with the established corpus spelling.", "Rule 198: ngala-ngala retained spelling."),
    ("lexicon", "Dayirr stayed clean/clear only; no new colour root or brightness expansion was admitted.", "Rule 198: dayirr clean/clear only."),
    ("lexicon", "Kambi rows retained clothing only; flying-fox homograph and material-source meanings stayed closed.", "Rule 198: kambi clothing only."),
    ("lexicon", "Bubu rows retained ground only; country, ownership, legal, and land-use readings stayed closed.", "Rule 198: bubu ground only."),
    ("lexicon", "Ngurrban rows retained cloud as an object noun only; no rain, storm, or weather-event predicate was added.", "Rule 198: ngurrban object restraint."),
    ("lexicon", "Karrambil rows retained king parrot as an object noun only; no flying, feather, food, story, or omen row was added.", "Rule 198: karrambil object restraint."),
    ("morphology", "All target adjectives stayed bare in object NPs: no case, degree, comparison, causative, inchoative, plural, compound, or -kari.", "Rule 198: bare target adjectives."),
    ("morphology", "Nyaji-l was represented as nonpast nyajil and past nyajin; analysis used nyaji-l and nyaji-ny consistently with earlier batches.", "Rule 198: perception tense discipline."),
    ("syntax", "Rows 1-10 used Ngayu NP ADJ nyajil with no local demonstrative.", "Rule 198: 1sg nonpast perception."),
    ("syntax", "Rows 11-20 used Yundu NP ADJ nyajil with no local demonstrative.", "Rule 198: 2sg nonpast perception."),
    ("syntax", "Rows 21-30 used Jana NP ADJ nyajin with past perception only.", "Rule 198: 3pl past perception."),
    ("syntax", "Rows 31-40 used Ngana NP ADJ yaluy nyajil.", "Rule 198: inclusive we plus here support."),
    ("syntax", "Rows 41-50 used Yundu NP ADJ yinyay nyajil.", "Rule 198: 2sg plus there support."),
    ("syntax", "All object NPs stayed unmarked and kept noun before adjective.", "Rule 198: object NP order."),
    ("fidelity", "English stayed visual and literal: see/saw plus the selected property noun phrases.", "Rule 198: literal visual English."),
    ("fidelity", "No English hearing/listening, not/without, white/pale, weather, ownership, food, flying, timber, cutting, making, or becoming content was imported.", "Rule 198: denied English fields."),
    ("register", "Rows remained plain descriptive perception clauses, not narrative, cultural, or ethnographic claims.", "Rule 198: descriptive perception register."),
    ("handoff", "Next batch should return to a lexical expansion or a targeted debt sweep; if continuing these heads, keep visual-property traps and kari drift closed.", "Rule 198: next cadence."),
]

LEXEMES = [
    ("ngumbu", "adjective", None, "NA", "black; dark", "batch-240: visual-property target inside perception object NPs; no ngumbu-kari or white/pale drift."),
    ("bingaji", "adjective", None, "NA", "light-coloured", "batch-240: adjective only inside perception object NPs; white-haired-person noun homograph closed."),
    ("ngala-ngala", "adjective", None, "NA", "red; reddish", "batch-240: red visual-property target inside perception object NPs."),
    ("dayirr", "adjective", None, "NA", "clean; clear", "batch-240: clean/clear target inside perception object NPs only."),
    ("kulji", "noun", None, "NA", "stone; pebbles", "batch-240: object noun with black property in perception rows."),
    ("juku", "noun", None, "NA", "tree; wood", "batch-240: object noun with black property; no material-use or cutting claim."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-240: object noun with dark property; no weather-event claim."),
    ("mungka", "noun", None, "NA", "hair", "batch-240: object noun with light-coloured property; no body-possession row."),
    ("kambi", "noun", None, "NA", "clothing", "batch-240: clothing object noun only; flying-fox homograph closed."),
    ("nganka", "noun", None, "NA", "flower; blossom", "batch-240: flower object noun with red property."),
    ("karrambil", "noun", None, "NA", "king parrot", "batch-240: bird object noun only; no bird-event semantics."),
    ("bana", "noun", None, "NA", "water", "batch-240: object noun with clear property only."),
    ("bubu", "noun", None, "NA", "ground; earth", "batch-240: ground object noun only; no country/ownership reading."),
    ("bayan", "noun", None, "NA", "house; camp; shelter", "batch-240: house object noun with clean property."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-240: bare pronoun A in nonpast visual perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-240: bare pronoun A in nonpast visual perception rows, including yinyay support."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-240: bare pronoun A in past visual perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-240: bare pronoun A in yaluy-supported nonpast visual perception rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-240: local demonstrative support in perception rows only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-240: distal local demonstrative support in perception rows only."),
    ("nyaji-l", "verb", None, "NA", "see; hear; perceive", "batch-240: visual perception verb; English constrained to see/saw in this batch."),
]


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-240-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 198 rows. Morphology checked target adjectives bare and nyaji-l tense forms. Lexicon checked selected visual-property senses and kept blocked colour, white/pale, homograph, weather, country, material, body-possession, and bird-event semantics closed. Syntax checked bare pronoun A, unmarked object NPs, noun-before-adjective order, nonpast nyajil, past nyajin, and yaluy/yinyay support. Fidelity checked visual see/saw English only. Register stayed descriptive.",
                 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 kari, -kari, ngumbu-kari, white/pale drift, waki, kambar, makirr, murbuy, wuba, mula-mula, marun-marun, jurrbil, green/blue/brown/purple/yellow field, wanka, warral, jarrmba, jinbal, jibarr, kunji, dalku, kubarr, jarrakulba, balbal, ngungul-ngungul, common-noun A, ERG marking, target case, degree, comparison, causative, inchoative, plural, target compound, productive reduplication, material-source, plant-use, body-possession, weather-event, bird-event, hearing/listening English, or land/country ownership 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 198 lessons covering source checks, kari exclusion, target senses, perception morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_240.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 198 visual-property adjectives, object nouns, pronoun/local-demonstrative support heads, and nyaji-l.",
                 artifact_path="batch_scripts/close_240.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 240: 50 accepted Rule 198 visual-property perception-consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_240.py", artifact_path="batch_scripts/close_240.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-240%'").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())
