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

NOTES = (
    "CONSTRUCTION CONSOLIDATION AFTER RULE 151 (Rule 152). 50 rows. TARGETS RETAINED: 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: present perception, bare past "
    "perception, and present/past perception with yinyay support. REVIEW: no new target heads; all targets stayed "
    "bare; no target case forms, compounds, 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 construction pass after a geography/water lexical expansion should retain target heads and vary only already-source-checked perception frames.", "Rule 152: construction after geography lexical pass."),
    ("process", "Rule 152 reused the exact Rule 151 target set and admitted no new target heads.", "Rule 152: no new targets."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 152: duplicate preflight."),
    ("lexicon", "`wawubaja` remained river/creek noun only; no river travel, swimming, fish, or crocodile inference.", "Rule 152: wawubaja retained."),
    ("lexicon", "`baral` remained road/path noun only; the homophonous feel verb and road-traversal frame stayed closed.", "Rule 152: baral noun retained."),
    ("lexicon", "`bana` remained water noun only; no taking, drinking, bathing, boiling, source, or water-use row.", "Rule 152: bana retained."),
    ("lexicon", "`jukar` remained sand noun only; no sandy derivation, wind, or fish-name compound.", "Rule 152: jukar retained."),
    ("lexicon", "`manjal` remained mountain noun only; no mountain-location, weather-strike, or climbing row.", "Rule 152: manjal retained."),
    ("lexicon", "`jalkaraburr` remained mountain-peak noun only; no climbing, height comparison, or place-name row.", "Rule 152: jalkaraburr retained."),
    ("lexicon", "`daburri` remained brackish swamp-water/swamp noun only; no ecology, animal, or danger inference.", "Rule 152: daburri retained."),
    ("lexicon", "`dajali` remained lexicalized deep water, not a free adjective `deep`.", "Rule 152: dajali retained."),
    ("lexicon", "`yalkan` remained lexicalized shallow water, not a free adjective `shallow`.", "Rule 152: yalkan retained."),
    ("lexicon", "`ngalkal` remained outside/open-ground noun only; no comitative group or social-territory derivation.", "Rule 152: ngalkal retained."),
    ("morphology", "All geography/water target heads stayed bare; no target LOC, DAT, ABL, PERL, INST, COMIT, POSS, or compound morphology appeared.", "Rule 152: target case restraint."),
    ("morphology", "Common-noun A in perception rows was ERG-marked; pronoun A rows stayed bare.", "Rule 152: A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 152: perception tense forms."),
    ("syntax", "Present perception rows used one bare target object plus `nyajil`.", "Rule 152: present perception syntax."),
    ("syntax", "Bare past perception rows used one bare target object plus `nyajin`.", "Rule 152: past perception syntax."),
    ("syntax", "Perception rows with `yinyay` added deictic support without target case morphology.", "Rule 152: deictic perception syntax."),
    ("syntax", "No row used a target locative, target perlative, target dative goal, or route construction.", "Rule 152: no route 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 152: selected-sense fidelity."),
    ("fidelity", "No travel/swimming/bathing/diving/drinking/water-taking/road-traversal frame was imported from grammar examples.", "Rule 152: no event import."),
    ("register", "Rows remained ordinary landscape/water perception statements.", "Rule 152: register scope."),
    ("handoff", "Next cadence may return to lexical expansion, but target geography case/travel/water-use should stay closed unless separately sourced.", "Rule 152: next cadence."),
    ("handoff", "Carry forward the traps: keep `wuburr` closed unless reconciled; keep `dajali` and `yalkan` as water-depth nouns.", "Rule 152: carry-forward traps."),
]

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