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

NOTES = (
    "GEOGRAPHY/WATER LEXICAL EXPANSION AFTER RULE 150 (Rule 151). 50 rows. TARGETS: wawubaja river, baral "
    "road/path, bana water, jukar sand, manjal mountain, jalkaraburr mountain peak, daburri brackish swamp water, "
    "dajali deep water, yalkan shallow water, ngalkal outside/open ground. FRAMES: bare deictic clauses, bare past "
    "perception, present perception, and past perception with yinyay. REVIEW: all targets stayed bare; no target "
    "case forms, compounds, locatives, perlatives, dative goals, ablatives, travel/swimming/bathing/diving/drinking/"
    "water-taking/road-traversal semantics, wuburr place-name/mountain-top trap, balay/dubar flat-place ambiguity, "
    "or carry-forward implement/action inference."
)

LESSONS = [
    ("process", "A lexical geography/water pass can add place heads without opening motion or case morphology.", "Rule 151: lexical before travel/case."),
    ("process", "Rule 151 excluded `wuburr` because the working dictionary marks it as place-name/mission despite grammar mountain-top examples.", "Rule 151: wuburr exclusion."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 151: duplicate preflight."),
    ("lexicon", "`wawubaja` was admitted as river/creek noun only; no river travel, swimming, fish, or crocodile inference.", "Rule 151: wawubaja lexical scope."),
    ("lexicon", "`baral` was admitted as road/path noun only; the homophonous feel verb and road-traversal frame stayed closed.", "Rule 151: baral noun selection."),
    ("lexicon", "`bana` was admitted as water noun only; no taking, drinking, bathing, boiling, or water-source row.", "Rule 151: bana lexical scope."),
    ("lexicon", "`jukar` was admitted as sand noun only; no sandy derivation or fish-name compound.", "Rule 151: jukar lexical scope."),
    ("lexicon", "`manjal` was admitted as mountain noun only; no mountain-location or weather-strike row.", "Rule 151: manjal lexical scope."),
    ("lexicon", "`jalkaraburr` was admitted as mountain-peak noun only; no inferred climbing, height comparison, or place-name row.", "Rule 151: jalkaraburr lexical scope."),
    ("lexicon", "`daburri` was admitted as brackish swamp-water/swamp noun only; no ecological, animal, or danger inference.", "Rule 151: daburri lexical scope."),
    ("lexicon", "`dajali` was admitted as lexicalized deep water, not as a free adjective `deep`.", "Rule 151: dajali lexicalized noun."),
    ("lexicon", "`yalkan` was admitted as lexicalized shallow water, not as a free adjective `shallow`.", "Rule 151: yalkan lexicalized noun."),
    ("lexicon", "`ngalkal` was admitted as outside/open-ground noun only; no comitative group or social-territory derivation.", "Rule 151: ngalkal lexical scope."),
    ("morphology", "All geography/water target heads remained bare; no target LOC, DAT, ABL, PERL, INST, COMIT, POSS, or compound morphology appeared.", "Rule 151: target case restraint."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 151: A marking."),
    ("morphology", "`nyajin` was kept as nyaji-ny past and `nyajil` as nyaji-l nonpast.", "Rule 151: perception tense forms."),
    ("syntax", "Bare deictic clauses used target noun plus `yinyay` only.", "Rule 151: deictic clause syntax."),
    ("syntax", "Bare past perception rows used one bare target object plus `nyajin`.", "Rule 151: past perception syntax."),
    ("syntax", "Present perception rows used one bare target object plus `nyajil`.", "Rule 151: present perception syntax."),
    ("syntax", "Past perception with `yinyay` added deictic support without target case morphology.", "Rule 151: deictic perception syntax."),
    ("fidelity", "English labels selected only the source-attested geography/water senses and did not add motion, use, danger, ecology, or place-name inference.", "Rule 151: selected-sense fidelity."),
    ("fidelity", "No travel/swimming/bathing/diving/drinking/water-taking/road-traversal frame was imported from grammar examples.", "Rule 151: no event import."),
    ("register", "Rows remained ordinary landscape/water identification and perception statements.", "Rule 151: register scope."),
    ("handoff", "Next cadence should consolidate these geography/water heads before opening any case-marked route, water-use, or travel construction.", "Rule 151: next cadence."),
    ("handoff", "Carry forward the traps: keep `wuburr` closed unless reconciled against dictionary evidence; keep `dajali` and `yalkan` as water-depth nouns.", "Rule 151: carry-forward traps."),
]

LEXEMES = [
    ("wawubaja", "noun", None, "NA", "river; creek", "batch-193: river/creek noun only; no travel/swimming/fishing/crocodile inference."),
    ("baral", "noun", None, "NA", "road; path", "batch-193: road/path noun only; homophonous feel verb and road-traversal frame closed."),
    ("bana", "noun", None, "NA", "water", "batch-193: water noun only; no taking/drinking/bathing/boiling/use row."),
    ("jukar", "noun", None, "NA", "sand", "batch-193: sand noun only; no sandy derivation or fish-name compound."),
    ("manjal", "noun", None, "NA", "mountain; range", "batch-193: mountain noun only; no target locative or weather/event row."),
    ("jalkaraburr", "noun", None, "NA", "mountain peak; high mountain reaches", "batch-193: mountain-peak noun only; no climbing/height/place-name inference."),
    ("daburri", "noun", None, "NA", "brackish swamp water; swamp", "batch-193: swamp noun only; no ecology/animal/danger inference."),
    ("dajali", "noun", None, "NA", "deep water", "batch-193: lexicalized deep-water noun; not a free adjective."),
    ("yalkan", "noun/adjective", None, "NA", "shallow water", "batch-193: lexicalized shallow-water expression; not a free adjective."),
    ("ngalkal", "noun", None, "NA", "outside; open ground", "batch-193: outside/open-ground noun only; no comitative/group-territory derivation."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-193: local demonstrative support in bare deictic and perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; hear; perceive", "batch-193: past and nonpast perception rows with geography/water objects."),
    ("ngamu", "noun", None, "NA", "mother", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("nganjan", "noun", None, "NA", "father", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("babi", "noun", None, "NA", "grandmother", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("karrkay", "noun", None, "NA", "child", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("kami", "noun", None, "NA", "grandfather", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("jalbu", "noun", None, "NA", "woman", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("dingkar", "noun", None, "NA", "man", "batch-193: common-noun A in perception rows, ERG-marked."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-193: bare pronoun A in perception rows."),
    ("ngana", "pronoun", None, "NA", "we; 1pl inclusive", "batch-193: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-193: bare pronoun A in 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-193-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 151 rows. Morphology checked all target heads bare, no "
            "target case/compound forms, common-noun A ERG, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. "
            "Lexicon checked geography/water senses, dajali/yalkan lexicalized water-depth nouns, baral road noun, "
            "and wuburr/balay/dubar exclusions. Syntax checked deictic clauses, bare past perception, present "
            "perception, and yinyay-supported past perception. Fidelity checked no motion/water-use/event import. "
            "Register stayed ordinary landscape identification and 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/instrument/comitative/possessive/"
            "compound form, no travel/swim/bathe/dive/drink/take/water-use/road-traversal event, no wuburr "
            "mountain-top/place-name row, no balay/dubar flat-place row, and no carry-forward implement/action "
            "semantics from Rules 149-150."
        ),
        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 151 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
        artifact_path="batch_scripts/close_193.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 151 targets, support forms, participants, and pronouns.",
        artifact_path="batch_scripts/close_193.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 193: 50 accepted Rule 151 geography/water lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_193.py",
        artifact_path="batch_scripts/close_193.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-193:%'").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, "
        f"{lexeme_logs} lexeme/source-log rows, {process_events} process events, "
        f"under_review={under_review_remaining}, verified corpus={verified}"
    )
    return 0


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