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

NOTES = (
    "LOW-COVERAGE SHELLFISH REFERENCE LEXICAL EXPANSION AFTER RULE 212 (Rule 213). 50 rows. TARGETS: "
    "baymbay large mud clam, darkay clam, kaduy snail, karraway snail, karruku ghost crab, kulil jellyfish, "
    "kuyalin small conical shellfish, marrkabina oyster, ngarrakaja shell fish, and nuwi squid. FRAMES: TARGET yaluy, "
    "TARGET yinyay, Yinya TARGET yinyay, TARGET yinya yinyay, and Yinya TARGET yaluy. REVIEW: all target nouns stayed "
    "bare absolutive reference heads; yinya/yaluy/yinyay stayed uninflected support only; English stayed literal "
    "here/there/that reference prose. No target case, possession, comitative, instrumental, locative, number, "
    "derivation, compound, productive reduplication, edible/food/eating, bait/use, cooking/frying, gathering/collecting, "
    "catching/fishing/spearing/netting, sea/reef/rock/night/habitat/water, shell/body-part, sting/burn/event, "
    "secondary-sense, Rule 212 insect drift, or support-inflection drift was opened."
)

LESSONS = [
    ("process", "Rule 213 used a low-coverage shellfish/crustacean reference lexical field after Rule 212 insect references.", "Rule 213: shellfish-reference cadence."),
    ("source", "Patz section 3.7 supports yinya 'that/those', yaluy 'here', and yinyay 'there'.", "Rule 213: demonstrative source."),
    ("source", "Patz section 3.7 permits yinya before or after a noun; Rule 213 kept both positions but no inflected demonstrative forms.", "Rule 213: yinya position."),
    ("process", "Shellfish/crustacean was admitted only after a fresh source pass found ten usable heads; edible, bait, use, and habitat prose stayed closed.", "Rule 213: shellfish admission."),
    ("process", "Body-part, physical-property, bodily-function, land/place, tool-implement, and action/event fields remained deferred because they require different constructions or reopen heavy traps.", "Rule 213: deferred fields."),
    ("process", "Shellfish candidates with unhyphenated reduplication, frying/sea-rock/prickle prose, or shell/body-part ambiguity were rejected or held in reserve.", "Rule 213: rejected shellfish candidates."),
    ("lexicon", "Baymbay stayed large mud clam only; mud/clam label did not license gathering, cooking, eating, sea, reef, or habitat rows.", "Rule 213: baymbay."),
    ("lexicon", "Darkay stayed clam only; small-mud-clam definition did not license gathering, cooking, eating, sea, reef, water, or habitat rows.", "Rule 213: darkay."),
    ("lexicon", "Kaduy stayed snail only; night/nocturnal detail in the definition stayed closed.", "Rule 213: kaduy."),
    ("lexicon", "Karraway stayed karraway snail/snail only; edible reading stayed closed.", "Rule 213: karraway."),
    ("lexicon", "Karruku stayed ghost crab only; fiddler-crab secondary label and movement/habitat prose stayed closed.", "Rule 213: karruku."),
    ("lexicon", "Kulil stayed jellyfish only; sting, burn, danger, and event readings stayed closed.", "Rule 213: kulil."),
    ("lexicon", "Kuyalin stayed small conical shellfish only; bait/use reading stayed closed.", "Rule 213: kuyalin."),
    ("lexicon", "Marrkabina stayed oyster only; edible reading stayed closed.", "Rule 213: marrkabina."),
    ("lexicon", "Ngarrakaja stayed shell fish only; species and edible details stayed closed.", "Rule 213: ngarrakaja."),
    ("lexicon", "Nuwi stayed squid only; fishing, catching, food, and water/habitat readings stayed closed.", "Rule 213: nuwi."),
    ("morphology", "All shellfish target nouns stayed bare: no case, possession, comitative, instrumental, locative, plural, derivation, compound, or suffixing.", "Rule 213: bare nouns."),
    ("morphology", "Productive and unhyphenated reduplication stayed closed; no shellfish reduplicated candidate was admitted.", "Rule 213: reduplication guard."),
    ("morphology", "Yinya, yaluy, and yinyay stayed uninflected; no demonstrative case, possessive, comitative, local-derived, or plural-human form was opened.", "Rule 213: support morphology."),
    ("syntax", "Rows 1-10 used TARGET yaluy.", "Rule 213: here frame."),
    ("syntax", "Rows 11-20 used TARGET yinyay.", "Rule 213: there frame."),
    ("syntax", "Rows 21-30 used Yinya TARGET yinyay.", "Rule 213: initial demonstrative there frame."),
    ("syntax", "Rows 31-40 used TARGET yinya yinyay.", "Rule 213: postposed demonstrative there frame."),
    ("syntax", "Rows 41-50 used Yinya TARGET yaluy.", "Rule 213: initial demonstrative here frame."),
    ("fidelity", "English stayed literal: selected shellfish/crustacean label plus here/there/that support only.", "Rule 213: literal English."),
    ("fidelity", "No English edible/food/eating, bait/use, cooking/frying, gathering/collecting, catching/fishing/spearing/netting, sea/reef/rock/night/habitat/water, shell/body-part, sting/burn, or event wording was imported.", "Rule 213: denied English fields."),
    ("register", "Rows remained plain reference/location sentences, not food-gathering statements, fishing reports, habitat descriptions, cooking statements, danger accounts, or ecological descriptions.", "Rule 213: register."),
    ("process", "Duplicate preflight, static guards, whole-corpus lint, five-lens review, lessons, lexeme logs, export, and live docs are required evidence before treating Rule 213 as complete.", "Rule 213: evidence standard."),
    ("handoff", "Next batch may continue from 12,847 if this closes; do not infer shellfish food, bait, fishing, habitat, body-part, event, or morphology from Rule 213.", "Rule 213: next cadence."),
]

LEXEMES = [
    ("baymbay", "noun", None, "NA", "large mud clam", "batch-255: large mud clam noun only; gathering/cooking/eating/sea/reef/habitat readings closed."),
    ("darkay", "noun", None, "NA", "clam", "batch-255: clam/small mud clam noun only; gathering/cooking/eating/sea/reef/water/habitat readings closed."),
    ("kaduy", "noun", None, "NA", "snail", "batch-255: snail noun only; night/nocturnal detail closed."),
    ("karraway", "noun", None, "NA", "snail", "batch-255: karraway snail/snail noun only; edible reading closed."),
    ("karruku", "noun", None, "NA", "ghost crab", "batch-255: ghost crab noun only; fiddler-crab secondary label and movement/habitat readings closed."),
    ("kulil", "noun", None, "NA", "jellyfish", "batch-255: jellyfish noun only; sting/burn/danger/event readings closed."),
    ("kuyalin", "noun", None, "NA", "small conical shellfish", "batch-255: small conical shellfish noun only; bait/use reading closed."),
    ("marrkabina", "noun", None, "NA", "oyster", "batch-255: oyster noun only; edible reading closed."),
    ("ngarrakaja", "noun", None, "NA", "shell fish", "batch-255: shell fish noun only; species/edible details closed."),
    ("nuwi", "noun", None, "NA", "squid", "batch-255: squid noun only; fishing/catching/food/water/habitat readings closed."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-255: local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-255: local demonstrative support only."),
    ("yinya", "demonstrative", None, "NA", "that; those", "batch-255: distal demonstrative support only, before or after noun; no 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-255-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 213 rows. Morphology checked bare shellfish/crustacean targets and uninflected yinya/yaluy/yinyay. Lexicon checked selected shellfish labels only. Syntax checked five deictic/reference frames. Fidelity checked literal here/there/that English. Register stayed plain reference/location.",
        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 case, possession, comitative, instrumental, locative, plural, derivation, compound, productive reduplication, edible/food/eating, bait/use, cooking/frying, gathering/collecting, catching/fishing/spearing/netting, sea/reef/rock/night/habitat/water, shell/body-part, sting/burn/event, secondary-sense, Rule 212 insect drift, 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 213 lessons covering source checks, field rejection, target senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_255.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 213 targets and demonstrative heads.",
        artifact_path="batch_scripts/close_255.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 255: 50 accepted Rule 213 low-coverage shellfish reference lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_255.py",
        artifact_path="batch_scripts/close_255.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_after, words_after = db.execute(
        """
        SELECT
          COUNT(*),
          SUM(LENGTH(kuku)-LENGTH(REPLACE(kuku,' ',''))+1)
        FROM sentences
        WHERE status IN ('accepted','revised')
        """
    ).fetchone()
    print(
        f"closed {LABEL}: accepted=50, reviews={reviews}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before}->{words_after}"
    )
    return 0


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