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

NOTES = (
    "VISUAL/COLOUR PROPERTY LEXICAL EXPANSION AFTER RULE 196 (Rule 197). 50 rows. TARGETS: ngumbu black/dark, "
    "bingaji light-coloured, ngala-ngala red, and dayirr clean/clear. SUBJECTS: kulji stone, juku tree, ngurrban "
    "cloud, mungka hair, kambi clothing, nganka flower, karrambil king parrot, bana water, bubu ground, and bayan "
    "house. FRAMES: yala NP ADJ, bare NP ADJ yaluy, yinya NP ADJ yinyay, bare NP ADJ yinyay, and yala NP ADJ "
    "yaluy. REVIEW: no green/blue/brown/purple/yellow/white-loan field, waki, kambar, makirr, murbuy, wuba, "
    "mula-mula, marun-marun, jurrbil, wanka, warral, jarrmba, jinbal, jibarr, kunji, dalku, kubarr, jarrakulba, "
    "balbal, ngungul-ngungul, case, degree, comparison, causative, inchoative, plural, target compound, productive "
    "reduplication, body-possession, weather-event, bird-event, material-use, or country/ownership row was opened."
)

LESSONS = [
    ("process", "Rule 197 returned to lexical expansion after Rule 196, but kept the same proven property/deictic frames.", "Rule 197: lexical cadence after Rule 196."),
    ("process", "The field was narrowed to visual-property adjectives with explicit Patz/dictionary support.", "Rule 197: source-bounded target field."),
    ("process", "Draft Kambi dayirr yinyay was rejected as a duplicate of Batch 146 row 9.", "Rule 197: duplicate avoidance."),
    ("lexicon", "Ngumbu was admitted only as black/dark property, not night/darkness setting or sea-snake ngumbul.", "Rule 197: ngumbu discipline."),
    ("lexicon", "Bingaji was admitted only as light-coloured adjective; the white-haired-person noun homograph stayed closed.", "Rule 197: bingaji adjective only."),
    ("lexicon", "Ngala-ngala was admitted as red/reddish using established corpus spelling; no new red variants were opened.", "Rule 197: ngala-ngala spelling and scope."),
    ("lexicon", "Dayirr was admitted only as clean/clear property; no new colour-root or sun-shortcut use was opened.", "Rule 197: dayirr clean/clear only."),
    ("lexicon", "Kambi rows used the clothing sense only; flying-fox homograph and material-source semantics stayed closed.", "Rule 197: kambi clothing only."),
    ("lexicon", "Bubu rows used ground only; country, ownership, legal, and land-use readings stayed closed.", "Rule 197: bubu ground only."),
    ("lexicon", "Ngurrban rows used cloud only; no rain, storm, coming-weather, or weather-event predicate was added.", "Rule 197: cloud noun restraint."),
    ("lexicon", "Karrambil rows used king parrot as a noun only; no flying, feather, food, story, or omen row was added.", "Rule 197: bird-event restraint."),
    ("morphology", "All target adjectives stayed bare: no case, degree, comparison, causative, inchoative, plural, -kari, or target compound.", "Rule 197: bare target morphology."),
    ("morphology", "Reduplicated lexical roots ngala-ngala remained lexicalized; no productive reduplication was created.", "Rule 197: lexicalized reduplication only."),
    ("syntax", "Rows 1-10 used yala NP ADJ predicates.", "Rule 197: yala NP ADJ."),
    ("syntax", "Rows 11-20 used bare NP ADJ yaluy predicates.", "Rule 197: NP ADJ yaluy."),
    ("syntax", "Rows 21-30 used yinya NP ADJ yinyay predicates.", "Rule 197: yinya NP ADJ yinyay."),
    ("syntax", "Rows 31-40 used bare NP ADJ yinyay predicates.", "Rule 197: NP ADJ yinyay."),
    ("syntax", "Rows 41-50 used yala NP ADJ yaluy predicates.", "Rule 197: yala NP ADJ yaluy."),
    ("fidelity", "English stayed literal: this/that/here/there plus selected visual-property senses.", "Rule 197: literal English."),
    ("fidelity", "No English green, blue, brown, purple, yellow, white, ochre, clay, shine, burn, weather, food, or ownership content was imported.", "Rule 197: denied English fields."),
    ("register", "Rows remained plain descriptive property clauses, not narrative or cultural claims.", "Rule 197: descriptive register."),
    ("handoff", "Next batch may consolidate Rule 197 visual-property heads in a different safe construction or return to a new bounded lexical field.", "Rule 197: next cadence."),
]

LEXEMES = [
    ("ngumbu", "adjective", None, "NA", "black; dark", "batch-239: visual-property target; no night/darkness setting or ngumbul drift."),
    ("bingaji", "adjective", None, "NA", "light-coloured", "batch-239: adjective only; white-haired-person noun homograph closed."),
    ("ngala-ngala", "adjective", None, "NA", "red; reddish", "batch-239: red visual-property target using established corpus spelling."),
    ("dayirr", "adjective", None, "NA", "clean; clear", "batch-239: clean/clear target only; no new colour root."),
    ("kulji", "noun", None, "NA", "stone; pebbles", "batch-239: subject noun for black property only."),
    ("juku", "noun", None, "NA", "tree; wood", "batch-239: subject noun only; no material-use or cutting claim."),
    ("ngurrban", "noun", None, "NA", "cloud", "batch-239: subject noun only; no weather-event claim."),
    ("mungka", "noun", None, "NA", "hair", "batch-239: subject noun only; no body-possession row."),
    ("kambi", "noun", None, "NA", "clothing", "batch-239: clothing sense only; flying-fox homograph closed."),
    ("nganka", "noun", None, "NA", "flower; blossom", "batch-239: flower subject only; no plant-event morphology."),
    ("karrambil", "noun", None, "NA", "king parrot", "batch-239: bird subject only; no bird-event semantics."),
    ("bana", "noun", None, "NA", "water", "batch-239: subject noun for clear property only."),
    ("bubu", "noun", None, "NA", "ground; earth", "batch-239: ground subject only; no country/ownership reading."),
    ("bayan", "noun", None, "NA", "house; camp; shelter", "batch-239: house subject only."),
    ("yala", "demonstrative", None, "NA", "this; here", "batch-239: support demonstrative only."),
    ("yinya", "demonstrative", None, "NA", "that; there", "batch-239: support demonstrative only."),
    ("yaluy", "demonstrative", None, "NA", "here; this place", "batch-239: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-239: local demonstrative support only."),
]


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-239-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 197 rows. Morphology checked all target adjectives remained bare with no case/degree/comparison/causative/inchoative/plural/compound/reduplication/-kari. Lexicon checked selected visual-property senses and kept colour phantoms, white/ochre/clay variants, homographs, body-possession, country, weather, bird-event, and material-use semantics closed. Syntax checked yala NP ADJ, NP ADJ yaluy, yinya NP ADJ yinyay, NP ADJ yinyay, and yala NP ADJ yaluy frames. Fidelity checked literal visual-property English. 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 waki, kambar, makirr, murbuy, wuba, mula-mula, marun-marun, jurrbil, green/blue/brown/purple/yellow/white-loan field, wanka, warral, jarrmba, jinbal, jibarr, kunji, dalku, kubarr, jarrakulba, balbal, ngungul-ngungul, target locative/dative/ablative/perlative/instrumental/comitative/possessive, degree, comparison, causative, inchoative, plural, target compound, productive reduplication, privative, material-source, plant-use, body-possession, weather-event, bird-event, 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 197 lessons covering source checks, duplicate preflight, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_239.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 197 visual-property adjectives, subject nouns, and deictic support heads.",
                 artifact_path="batch_scripts/close_239.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 239: 50 accepted Rule 197 visual/colour property lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_239.py", artifact_path="batch_scripts/close_239.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-239%'").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())
