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

NOTES = (
    "LANDFORM/GEOGRAPHY COMPLEMENTARY PERCEPTION PRONOUN EXPANSION AFTER RULE 247 (Rule 248). 50 rows. "
    "TARGETS retained: mabil swamp, karrirrangkal coral, jalngarr flat rock, jinali smooth rock, kangku valley, "
    "yalmba seashore, kambal-kambal mud, jalkar high bank, janku hole, and jamba hillside. SUPPORT: bare "
    "nominative ngali, ngaliny, yubal, nganjin, and yurra plus yaluy/yinyay and nyajil. FRAMES: "
    "Ngali TARGET yinyay nyajil, Ngaliny TARGET yaluy nyajil, Yubal TARGET yinyay nyajil, "
    "Nganjin TARGET yaluy nyajil, and Yurra TARGET yinyay nyajil. REVIEW: no new landform lexeme, no place-name, "
    "route/travel/crossing, river/water-use, lime/source-material, reef/sea/collecting, ecology/habitat, "
    "climbing/falling/danger, ownership/dispute/legal/social, finding/peeping/causative, rubbish/debris/"
    "leaf-mould/growing-use, smooth-property, steep-property, mountain-pass route, cheek/body-part, beach-collecting, "
    "turtle/food/warning, burrow/nest/digging/ground-oven, root/under-tree, burning, social-metaphor, target case, "
    "target compound, productive reduplication, pronoun case, perception compound, support inflection, or recent "
    "dwelling/fire/body/fish/bird drift was opened."
)

LESSONS = [
    ("source", "Rule 248 retained the ten checked Rule 232 landform/geography noun heads: mabil, karrirrangkal, jalngarr, jinali, kangku, yalmba, kambal-kambal, jalkar, janku, and jamba.", "Rule 248: retained target inventory."),
    ("source", "Dictionary line readback confirmed mabil as swamp, karrirrangkal as coral, jalngarr as flat rock, jinali as smooth rock, kangku as valley, yalmba as seashore, kambal-kambal as mud, jalkar as high bank, janku as hole, and jamba as hillside.", "Rule 248: dictionary source readback."),
    ("source", "Direct dictionary readback used lines 17030-17038 for mabil, 13615-13624 for karrirrangkal, 7498-7506 for jalngarr, 9391-9399 for jinali, 13266-13275 for kangku, 29078-29087 for yalmba, 12962-12975 for kambal-kambal, 7429-7439 for jalkar, 8119-8127 for janku, and 7690-7703 for jamba.", "Rule 248: line-level source evidence."),
    ("source", "Patz section 3.5 Table 3.6 supplied the selected bare nominative pronouns ngali, ngaliny, yubal, nganjin, and yurra.", "Rule 248: pronoun source."),
    ("source", "Patz section 3.7 supplied Yalanji yaluy 'here' and yinyay 'there'; Rule 248 used only the bare local demonstratives and did not add case-marked local forms.", "Rule 248: demonstrative source."),
    ("source", "Patz section 3.8.3.2 supplied nyaji-l 'see'; Rule 248 used only nonpast nyajil and did not build perception compounds, past, purposive, or infinitive rows.", "Rule 248: perception source."),
    ("process", "Exact duplicate preflight over all 50 final Rule 248 Kuku surfaces returned no accepted, revised, or under-review collisions.", "Rule 248: duplicate preflight."),
    ("process", "Token-aware target coverage before banking after Rule 247 was mabil 16, karrirrangkal 16, jalngarr 18, jinali 18, kangku 17, yalmba 16, kambal-kambal 21, jalkar 28, janku 50, and jamba 37.", "Rule 248: target coverage audit."),
    ("process", "Pronoun coverage before banking was ngali 131, ngaliny 65, yubal 79, nganjin 81, and yurra 124; the batch added opposite-location signal for dual, exclusive, and second-plural nominative forms.", "Rule 248: pronoun coverage audit."),
    ("lexicon", "Mabil remained swamp only; crossing, route, water-use, habitat, ecology, and event rows stayed closed.", "Rule 248: mabil."),
    ("lexicon", "Karrirrangkal remained coral only; lime, source-material, reef, sea, collecting, habitat, and material-use prose stayed closed.", "Rule 248: karrirrangkal."),
    ("lexicon", "Jalngarr remained flat rock only; sitting, creek, water, route, and event rows stayed closed.", "Rule 248: jalngarr."),
    ("lexicon", "Jinali remained smooth rock only; smooth-property predicates and smoothing-use rows stayed closed.", "Rule 248: jinali."),
    ("lexicon", "Kangku remained valley only; mountain-pass route/travel and kangkul cheek/body-part drift stayed closed.", "Rule 248: kangku."),
    ("lexicon", "Yalmba remained seashore only; beach-collecting, sea/tide events, turtle, food, and warning rows stayed closed.", "Rule 248: yalmba."),
    ("lexicon", "Kambal-kambal remained mud as a whole lexical reduplicated head; productive reduplication from kambal stayed closed.", "Rule 248: kambal-kambal."),
    ("lexicon", "Jalkar remained high bank only; jalkar-jalkar steep-property, river-route, and danger rows stayed closed.", "Rule 248: jalkar."),
    ("lexicon", "Janku remained hole only; waterhole, animal burrow, nest, digging, ground-oven, and event rows stayed closed.", "Rule 248: janku."),
    ("lexicon", "Jamba remained hillside only; locative/example-case import, root/under-tree drift, burning, social metaphor, and event rows stayed closed.", "Rule 248: jamba."),
    ("morphology", "All Rule 248 target nouns stayed bare: no LOC, DAT, ABL, PERL, ERG, INST, COMIT, POSS, PRIV, EXCESS, plural, derivation, or target suffix was admitted.", "Rule 248: bare targets."),
    ("morphology", "The subject support forms stayed bare nominatives: no pronoun case forms, possessive readings, or person/number extensions were introduced.", "Rule 248: bare nominative pronouns."),
    ("morphology", "Yaluy, yinyay, and nyajil stayed uninflected support heads; no demonstrative case, local-derived form, verb nominalization, purposive, past, or support suffix was admitted.", "Rule 248: uninflected support."),
    ("morphology", "No target compound, lexicalized trap compound, place-name compound, or productive reduplication was built from the landform/geography heads.", "Rule 248: no compounds or reduplication."),
    ("syntax", "Rows 1-10 used Ngali TARGET yinyay nyajil.", "Rule 248: 1du exclusive there perception band."),
    ("syntax", "Rows 11-20 used Ngaliny TARGET yaluy nyajil.", "Rule 248: 1du inclusive here perception band."),
    ("syntax", "Rows 21-30 used Yubal TARGET yinyay nyajil.", "Rule 248: 2du there perception band."),
    ("syntax", "Rows 31-40 used Nganjin TARGET yaluy nyajil.", "Rule 248: 1pl exclusive here perception band."),
    ("syntax", "Rows 41-50 used Yurra TARGET yinyay nyajil.", "Rule 248: 2pl there perception band."),
    ("fidelity", "English stayed literal perception/reference prose: selected subject pronoun value, target label, here/there, and see only.", "Rule 248: literal English."),
    ("fidelity", "The batch did not convert dictionary examples or source prose into route, water-use, lime/source-material, reef/sea, collecting, habitat, ecology, danger, legal/social, property, body-part, or event claims.", "Rule 248: source-prose restraint."),
    ("register", "Rows remained plain elicitation-style perception clauses; no travel narrative, legal dispute, ecological description, warning, ceremony, place-name, or source-material register was introduced.", "Rule 248: register."),
    ("process", "Rules 149-247 carry-forward traps stayed closed, especially recent dwelling, fire, body-part, fish, and bird perception traps plus landform route/water-use/source-prose traps.", "Rule 248: carry-forward closure."),
    ("handoff", "Next batch may continue from 14,597 if this closes; do not infer route/travel, water-use, place-name, source-material, ecological, event, target-case, pronoun-case, perception-compound, or support-inflection grammar from Rule 248.", "Rule 248: next cadence."),
]

LEXEMES = [
    ("mabil", "noun", None, "NA", "swamp", "batch-290: swamp perception/reference only; no crossing, route, water-use, habitat, ecology, or event row."),
    ("karrirrangkal", "noun", None, "NA", "coral", "batch-290: coral perception/reference only; lime, source-material, reef, sea, collecting, habitat, and material-use rows closed."),
    ("jalngarr", "noun", None, "NA", "flat rock", "batch-290: flat-rock perception/reference only; no sitting, creek, water, route, or event row."),
    ("jinali", "noun", None, "NA", "smooth rock", "batch-290: smooth-rock perception/reference only; no smooth-property predicate or smoothing-use row."),
    ("kangku", "noun", None, "NA", "valley", "batch-290: valley perception/reference only; mountain-pass route/travel and kangkul cheek drift closed."),
    ("yalmba", "noun", None, "NA", "seashore", "batch-290: seashore perception/reference only; beach-collecting, sea/tide event, turtle, food, and warning rows closed."),
    ("kambal-kambal", "noun", None, "NA", "mud", "batch-290: mud perception/reference only; lexical reduplicated head, no productive reduplication from kambal."),
    ("jalkar", "noun", None, "NA", "high bank", "batch-290: high-bank perception/reference only; jalkar-jalkar steep-property, river-route, and danger rows closed."),
    ("janku", "noun", None, "NA", "hole", "batch-290: hole perception/reference only; waterhole, burrow, nest, digging, ground-oven, and event rows closed."),
    ("jamba", "noun", None, "NA", "hillside", "batch-290: hillside perception/reference only; locative example import, root/under-tree, burning, social metaphor, and event rows closed."),
    ("ngali", "pronoun", None, "NA", "first dual exclusive nominative", "batch-290: bare nominative subject support only."),
    ("ngaliny", "pronoun", None, "NA", "first dual inclusive nominative", "batch-290: bare nominative subject support only."),
    ("yubal", "pronoun", None, "NA", "second dual nominative", "batch-290: bare nominative subject support only."),
    ("nganjin", "pronoun", None, "NA", "first plural exclusive nominative", "batch-290: bare nominative subject support only."),
    ("yurra", "pronoun", None, "NA", "second plural nominative", "batch-290: bare nominative subject support only."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-290: bare local demonstrative support only."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-290: bare local demonstrative support only."),
    ("nyajil", "verb", "l", "NA", "see", "batch-290: nonpast perception 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.execute("DELETE FROM lessons WHERE batch_id=?", (batch_id,))
    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-290-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 248 rows. Morphology checked bare landform nouns, bare nominative ngali/ngaliny/yubal/nganjin/yurra, bare yaluy/yinyay, and nyajil nonpast only. Lexicon checked selected target senses only. Syntax checked five opposite-location pronoun-perception frame bands. Fidelity checked literal reference/perception English. Register stayed plain elicitation-style.",
        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 place-name, route/travel/crossing, river/water-use, lime/source-material, reef/sea/collecting, ecology/habitat, climbing/falling/danger, ownership/dispute/legal/social, finding/peeping/causative, rubbish/debris/leaf-mould/growing-use, smooth-property, steep-property, mountain-pass route, cheek/body-part, beach-collecting, turtle/food/warning, burrow/nest/digging/ground-oven, root/under-tree, burning, social-metaphor, target case, productive compound, productive reduplication, pronoun case, perception compound, support inflection, or recent dwelling/fire/body/fish/bird drift.",
        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 248 lessons covering source checks, coverage, lexical target senses, morphology, syntax, fidelity, register, process traps, and handoff.",
        artifact_path="batch_scripts/close_290.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 248 targets and support heads.",
        artifact_path="batch_scripts/close_290.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 290: 50 accepted Rule 248 landform/geography complementary pronoun-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_290.py",
        artifact_path="batch_scripts/close_290.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]
    lessons = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (batch_id,)).fetchone()[0]
    lexeme_logs = db.execute(
        "SELECT COUNT(*) FROM lexeme_log WHERE action='batch-290-verify'"
    ).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}, lessons={lessons}, "
        f"lexeme_logs={lexeme_logs}, verified {verified_before}->{verified_after}, "
        f"kuku_words {words_before}->{words_after}"
    )
    return 0


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