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

NOTES = (
    "LANDFORM REFERENCE CONSTRUCTION CONSOLIDATION AFTER RULE 185 (Rule 186). 50 rows. TARGETS retained from Rule 185: "
    "binda-dijarr stony crossing, duli burnt patch of grass, jamar newly cleared scrub, kabay small ant bed, "
    "karrangkal reef, kuri small patch of scrub, ngamar cliff, nganyay desert, ngidin boundary, and warrmba exposed "
    "place. FRAMES: bare yinyay deictic identification, yaluy-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 new landform heads, place names, rejected "
    "candidates, route/travel/crossing-event, river/water-use, burning, clearing, live ant/insect behavior, ecology, "
    "coral/sea/collecting/habitat, climbing/falling/danger, heat/scarcity, ownership/dispute/legal/social, "
    "finding/peeping, causative, dialect-variant, rubbish/debris/beach-wrack/leaf-mould/growing-use, target case, "
    "target compound, plural derivation, productive reduplication, or event semantics."
)

LESSONS = [
    ("process", "A construction pass after Rule 185 retained exactly the selected landform-reference nouns.", "Rule 186: construction cadence after Rule 185."),
    ("process", "Rule 186 introduced no new landform heads; it only rotated yaluy/yinyay support around the existing Rule 185 set.", "Rule 186: no new lexical intake."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 186: duplicate preflight."),
    ("process", "The Batch 227 correction remains binding: `ngunnga` stays rejected after the locative-shaped lint failure, and `kabay` remains the selected replacement.", "Rule 186: correction carry-forward."),
    ("process", "`damu naka`, `kurrkal`, `nurru`, `nyamun`, `walba-murru`, and `yikin` remain rejected for ambiguity, route, corroboree-origin, debris/use, no-definition, or river/bank risk.", "Rule 186: rejected candidates carry-forward."),
    ("lexicon", "`binda-dijarr` remained stony crossing only; capitalized place-name and route/river-crossing event senses stayed closed.", "Rule 186: binda-dijarr."),
    ("lexicon", "`duli` remained burnt patch of grass only; no burning, fire, or ecology-event row.", "Rule 186: duli."),
    ("lexicon", "`jamar` remained newly cleared scrub only; no clearing action or land-use row.", "Rule 186: jamar."),
    ("lexicon", "`kabay` remained small ant bed only; no live ant, insect-behavior, ecology, or ant-bed-use row.", "Rule 186: kabay."),
    ("lexicon", "`karrangkal` remained reef only; coral, sea, water, collecting, and habitat claims stayed closed.", "Rule 186: karrangkal."),
    ("lexicon", "`kuri` remained small patch of scrub only; plant-use, ecology, and place-name claims stayed closed.", "Rule 186: kuri."),
    ("lexicon", "`ngamar` remained cliff only; climbing, falling, steep-route, and danger claims stayed closed.", "Rule 186: ngamar."),
    ("lexicon", "`nganyay` remained desert only; heat, travel, scarcity, and place-name claims stayed closed.", "Rule 186: nganyay."),
    ("lexicon", "`ngidin` remained boundary only; ownership, dispute, border-crossing, and legal/social claims stayed closed.", "Rule 186: ngidin."),
    ("lexicon", "`warrmba` remained exposed place only; `warrmba-bungal`, finding, peeping, and causative rows stayed closed.", "Rule 186: warrmba."),
    ("morphology", "All target heads stayed bare; no target LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, reduplicated, or compound morphology was produced.", "Rule 186: target case restraint."),
    ("morphology", "`binda-dijarr` stayed a lexical hyphenated dictionary head, not productive compounding.", "Rule 186: lexical hyphenation."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 186: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 186: perception tense forms."),
    ("syntax", "Rows 1-10 used one landform target plus `yinyay` with no predicator.", "Rule 186: yinyay deictic syntax."),
    ("syntax", "Rows 11-20 used bare 1sg A plus one bare landform object, `yaluy`, and `nyajil`.", "Rule 186: ngayu yaluy perception."),
    ("syntax", "Rows 21-30 used bare 2sg A plus one bare landform object, `yaluy`, and `nyajil`.", "Rule 186: yundu yaluy perception."),
    ("syntax", "Rows 31-40 used bare 3pl A plus one bare landform object, `yaluy`, and past `nyajin`.", "Rule 186: jana yaluy past perception."),
    ("syntax", "Rows 41-50 used inclusive `ngana`, one bare landform object, `yinyay`, and `nyajil`.", "Rule 186: ngana yinyay perception."),
    ("handoff", "Next cadence can move to a new lexical expansion only after a fresh source pass; landform route, water, place-name, ecology, event, target-case, and rejected-candidate traps remain closed unless deliberately sourced.", "Rule 186: next cadence."),
]

LEXEMES = [
    ("binda-dijarr", "noun", None, "NA", "stony crossing", "batch-228: retained stony crossing only in construction consolidation; capitalized place-name and route/river-crossing event senses closed."),
    ("duli", "noun", None, "NA", "burnt patch of grass", "batch-228: retained burnt patch of grass only; no burning, fire, or ecology event row."),
    ("jamar", "noun", None, "NA", "newly cleared scrub", "batch-228: retained newly cleared scrub only; no clearing action or land-use row."),
    ("kabay", "noun", None, "NA", "small ant bed", "batch-228: retained small ant bed only; no live ant, insect-behavior, ecology, or ant-bed-use row."),
    ("karrangkal", "noun", None, "NA", "reef", "batch-228: retained reef only; coral, sea, water, collecting, and habitat claims closed."),
    ("kuri", "noun", None, "NA", "small patch of scrub", "batch-228: retained small patch of scrub only; no plant-use, ecology, or place-name row."),
    ("ngamar", "noun", None, "NA", "cliff", "batch-228: retained cliff only; no climbing, falling, steep-route, or danger row."),
    ("nganyay", "noun", None, "NA", "desert", "batch-228: retained desert only; no heat, travel, scarcity, or place-name row."),
    ("ngidin", "noun", None, "NA", "boundary", "batch-228: retained boundary only; no ownership, dispute, border-crossing, or legal/social row."),
    ("warrmba", "noun", None, "NA", "exposed place", "batch-228: retained exposed place only; no warrmba-bungal, finding, peeping, or causative row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-228: retained local demonstrative in supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-228: retained local demonstrative in deictic and supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-228: retained past and nonpast perception rows with landform nouns."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-228: bare pronoun A in yaluy-supported present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-228: bare pronoun A in yaluy-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-228: bare pronoun A in yaluy-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-228: bare pronoun A in yinyay-supported present 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-228-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 186 rows. Morphology checked bare landform targets, no target case/compound/possessive/instrument/comitative/plural/productive-reduplication forms, binda-dijarr as lexical hyphenated head, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked retained landform senses and kept place names, rejected candidates, route/travel/crossing-event, river/water-use, burning, clearing, live ant/insect behavior, ecology, coral/sea/collecting/habitat, climbing/falling/danger, heat/scarcity, ownership/dispute/legal/social, finding/peeping, causative, dialect-variant, rubbish/debris/beach-wrack/leaf-mould/growing-use, target-case, and event traps closed. Syntax checked bare yinyay deictic identification, yaluy-supported present perception, yaluy-supported past perception, and yinyay-supported present perception. Fidelity checked no source-prose use import. Register stayed ordinary reference/perception.",
                 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/perlative/ergative/instrument/comitative/possessive/privative/excess/plural/productive-reduplication/compound form, no new landform head, no place-name/route/water/fire/clearing/insect-behavior/ecology/coral/sea/climbing/danger/ownership/dispute/find/peep/causative/event claim, and no rejected candidate.",
                 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 186 lessons covering source checks, construction scope, correction carry-forward, rejected candidates, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_228.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 186 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_228.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 228: 50 accepted Rule 186 landform reference construction consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_228.py", artifact_path="batch_scripts/close_228.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-228%'").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())
