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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 179 (Rule 180). 50 rows. TARGETS retained from Rule 179: badibu spotted "
    "eagle ray, bilaji flat-tailed ray, bunjulu giant herring, jilngu tarpon, karrulji black spotted dart, kilkirr "
    "tiger shark, midir knight fish, ngarmu shovelnose ray, yalnganji manta ray, and yubuji sawfish. 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 fish heads, catching, netting, hook/line, spearing, eating, cooking, food, taboo, "
    "storm/thunder, story, place, water/river/sea/habitat, fish body-part terms, target case, target compound, "
    "possession, plural derivation, or event semantics."
)

LESSONS = [
    ("process", "A construction pass after Rule 179 retained exactly the selected fish/ray reference nouns.", "Rule 180: construction cadence after Rule 179."),
    ("process", "Rule 180 introduced no new fish heads; it only rotated yaluy/yinyay support around the existing Rule 179 set.", "Rule 180: no new lexical intake."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 180: duplicate preflight."),
    ("process", "The reviewed-but-not-selected Rule 179 fish heads remained excluded through this consolidation pass.", "Rule 180: rejected candidate carry-forward."),
    ("process", "Fish/ray rows stayed ordinary reference and perception; fishing, food, storm, water, place, story, body-part, and event prose stayed closed.", "Rule 180: fish-use exclusion."),
    ("lexicon", "`badibu` remained spotted eagle ray only; no ray-catching, food, water, or event row.", "Rule 180: badibu."),
    ("lexicon", "`bilaji` remained flat-tailed ray only; no tail/body-part row beyond the lexical English label.", "Rule 180: bilaji."),
    ("lexicon", "`bunjulu` remained giant herring only; empty duplicate entry is not a production head.", "Rule 180: bunjulu."),
    ("lexicon", "`jilngu` remained tarpon only; boney-salmon/ox-eye-herring alternate prose stayed closed.", "Rule 180: jilngu."),
    ("lexicon", "`karrulji` remained black spotted dart only; no colour predicate or dart/action row.", "Rule 180: karrulji."),
    ("lexicon", "`kilkirr` remained tiger shark only; no danger, biting, hunting, or event row.", "Rule 180: kilkirr."),
    ("lexicon", "`midir` remained knight fish only; port-and-light alternate label stayed closed.", "Rule 180: midir."),
    ("lexicon", "`ngarmu` remained shovelnose ray only; no nose/body-part row beyond the lexical English label.", "Rule 180: ngarmu."),
    ("lexicon", "`yalnganji` remained Yalanji manta ray only; Nyungkul `yidi` and spotted-manta `yidilnyul` stayed closed.", "Rule 180: yalnganji."),
    ("lexicon", "`yubuji` remained sawfish only; no cutting/saw/action row.", "Rule 180: yubuji."),
    ("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 180: target case restraint."),
    ("morphology", "Pronoun A forms `ngayu`, `yundu`, `jana`, and `ngana` stayed bare.", "Rule 180: pronoun A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 180: perception tense forms."),
    ("morphology", "`yaluy` and `yinyay` stayed uninflected local demonstratives.", "Rule 180: local demonstrative restraint."),
    ("syntax", "Rows 1-10 used one fish/ray target plus `yinyay` with no predicator.", "Rule 180: yinyay deictic syntax."),
    ("syntax", "Rows 11-20 used bare 1sg A plus one bare fish/ray object, `yaluy`, and `nyajil`.", "Rule 180: ngayu yaluy perception."),
    ("syntax", "Rows 21-30 used bare 2sg A, one bare fish/ray object, `yaluy`, and `nyajil`.", "Rule 180: yundu yaluy perception."),
    ("syntax", "Rows 31-40 used bare 3pl A, one bare fish/ray object, `yaluy`, and past `nyajin`.", "Rule 180: jana yaluy past perception."),
    ("syntax", "Rows 41-50 used inclusive `ngana`, one bare fish/ray object, `yinyay`, and `nyajil`.", "Rule 180: ngana yinyay perception."),
    ("handoff", "Next cadence can return to lexical expansion, but Rule 179 fishing, food, storm, water, story, body-part, target-case, and event traps remain closed unless deliberately sourced.", "Rule 180: next cadence."),
]

LEXEMES = [
    ("badibu", "noun", None, "NA", "spotted eagle ray", "batch-222: retained spotted eagle ray only in construction consolidation; no ray-catching, food, water, or event row."),
    ("bilaji", "noun", None, "NA", "flat-tailed ray", "batch-222: retained flat-tailed ray only; no tail/body-part analysis beyond the lexical English label."),
    ("bunjulu", "noun", None, "NA", "giant herring", "batch-222: retained giant herring only; empty duplicate entry not used."),
    ("jilngu", "noun", None, "NA", "tarpon", "batch-222: retained tarpon only; boney-salmon/ox-eye-herring alternate prose closed."),
    ("karrulji", "noun", None, "NA", "black spotted dart", "batch-222: retained black spotted dart only; no colour predicate or dart/action row."),
    ("kilkirr", "noun", None, "NA", "tiger shark", "batch-222: retained tiger shark only; no danger, biting, hunting, or event row."),
    ("midir", "noun", None, "NA", "knight fish", "batch-222: retained knight fish only; port-and-light alternate label closed."),
    ("ngarmu", "noun", None, "NA", "shovelnose ray", "batch-222: retained shovelnose ray only; no nose/body-part analysis beyond the lexical English label."),
    ("yalnganji", "noun", None, "NA", "manta ray", "batch-222: retained Yalanji manta ray only; Nyungkul yidi and spotted-manta yidilnyul closed."),
    ("yubuji", "noun", None, "NA", "sawfish", "batch-222: retained sawfish only; no cutting/saw/action row."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-222: retained local demonstrative in supported perception rows."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-222: retained local demonstrative in deictic and supported perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-222: retained past and nonpast perception rows with fish/ray objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-222: bare pronoun A in yaluy-supported present perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-222: bare pronoun A in yaluy-supported present perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-222: bare pronoun A in yaluy-supported past perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-222: 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-222-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)",
                 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 180 rows. Morphology checked bare fish/ray targets, no target case/compound/possessive/instrument/comitative/plural/reduplicated forms, yinyay/yaluy support only, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked retained fish/ray senses and kept nonselected fish heads, fishing gear, catching, spearing, eating, food, taboo, storm/thunder, story, place, water/river/sea/habitat, fish body-part, and target-case 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/reduplicated/compound form, no new fish head, no fishing/use/food/storm/water/body-part/event claim, and no nonselected fish target.",
                 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 180 lessons covering source checks, construction scope, target senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_222.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 180 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_222.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 222: 50 accepted Rule 180 fish/ray construction consolidation rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_222.py", artifact_path="batch_scripts/close_222.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 detail LIKE '%batch-222:%'").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())
