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

NOTES = (
    "PLANT-RESOURCE LEXICAL EXPANSION AFTER RULE 154 (Rule 155). 50 rows. TARGETS: kabal Leichhardt tree, "
    "jujabala ironwood tree, kangka wild grape, nganjirr grass tree, junda wild plum, jikan grass, buyku paperbark, "
    "kanunjul grass-tree resin, yibuy loya cane, wukay hairy yam. FRAMES: bare deictic identification with yinyay, "
    "present/past perception with yaluy support. REVIEW: all targets stayed bare; no target case forms, compounds, "
    "dig/eat/gather/burn/scrape/chop/weave/tie/cook predicates, medicine preparation, material-source claims, "
    "weather-event/storm-control claims, or carry-forward weather/geography/implement inference."
)

LESSONS = [
    ("process", "A plant-resource lexical pass can grow vocabulary safely by using deictic and perception frames before opening harvesting or use predicates.", "Rule 155: lexical before plant-use."),
    ("process", "Rule 155 admitted ten plant-resource targets and kept all target heads bare.", "Rule 155: target inventory."),
    ("process", "Exact duplicate preflight found 50 planned rows, 50 unique surfaces, and no cross-corpus duplicates before banking.", "Rule 155: duplicate preflight."),
    ("lexicon", "`kabal` was admitted as Leichhardt tree only; no fruit-finding or medicine row.", "Rule 155: kabal lexical scope."),
    ("lexicon", "`jujabala` was admitted as ironwood tree only; no anti-thunderstorm burning row.", "Rule 155: jujabala lexical scope."),
    ("lexicon", "`kangka` was admitted as wild grape only; no burning, vine-use, or storm-control row.", "Rule 155: kangka lexical scope."),
    ("lexicon", "`nganjirr` was admitted as grass tree only; no burning or ritual-use row.", "Rule 155: nganjirr lexical scope."),
    ("lexicon", "`junda` was admitted as wild plum only; no gathering, eating, or fig-translation drift row.", "Rule 155: junda lexical scope."),
    ("lexicon", "`jikan` was admitted as grass only; no walking-through, snake, feed, or burning frame.", "Rule 155: jikan lexical scope."),
    ("lexicon", "`buyku` was admitted as paperbark only; no covering, roof, carrier, or bark-use row.", "Rule 155: buyku lexical scope."),
    ("lexicon", "`kanunjul` was admitted as grass-tree resin only; no burning or storm-control row.", "Rule 155: kanunjul lexical scope."),
    ("lexicon", "`yibuy` was admitted as loya cane only; no weaving, tying, walking-stick, or material-source row.", "Rule 155: yibuy lexical scope."),
    ("lexicon", "`wukay` was admitted as hairy yam only; no digging, eating, cooking, or searching row.", "Rule 155: wukay lexical scope."),
    ("morphology", "All plant-resource target heads stayed bare; no target LOC, DAT, ABL, PERL, INST, COMIT, POSS, or compound morphology appeared.", "Rule 155: target case restraint."),
    ("morphology", "Common-noun A `ngamu-ngku` was ERG-marked; pronoun A `ngayu`, `yundu`, and `jana` stayed bare.", "Rule 155: A marking."),
    ("morphology", "`nyajin` remained nyaji-ny past and `nyajil` remained nyaji-l nonpast.", "Rule 155: perception tense forms."),
    ("syntax", "Bare deictic rows used one plant-resource target plus `yinyay` and no predicator.", "Rule 155: deictic syntax."),
    ("syntax", "Present perception rows used one bare plant-resource object plus `yaluy` and `nyajil`.", "Rule 155: present perception syntax."),
    ("syntax", "Past perception rows used one bare plant-resource object plus `yaluy` and `nyajin`.", "Rule 155: past perception syntax."),
    ("syntax", "No row used harvesting, processing, medicine, burning, source-material, or food-use syntax.", "Rule 155: no use syntax."),
    ("fidelity", "English labels selected only source-attested plant-resource senses and did not add action, medicinal, ritual, weather, or material-use inference.", "Rule 155: selected-sense fidelity."),
    ("fidelity", "No plant-use or weather/storm-control claim was imported from grammar or dictionary prose examples.", "Rule 155: no source-event import."),
    ("register", "Rows remained ordinary plant-resource deictic/perception statements.", "Rule 155: register scope."),
    ("handoff", "Next cadence should consolidate these plant-resource heads before opening harvesting, food-use, medicine, or material-source predicates.", "Rule 155: next cadence."),
    ("handoff", "Carry forward plant-use traps: keep jujabala/kangka/nganjirr/kanunjul burning claims, wukay digging/eating, and buyku/yibuy material-use claims closed unless deliberately sourced.", "Rule 155: carry-forward traps."),
]

LEXEMES = [
    ("kabal", "noun", None, "NA", "Leichhardt tree", "batch-197: Leichhardt tree only; no fruit-finding/medicine row."),
    ("jujabala", "noun", None, "NA", "ironwood tree", "batch-197: ironwood tree only; no anti-thunderstorm burning row."),
    ("kangka", "noun", None, "NA", "wild grape", "batch-197: wild grape only; no burning/vine-use/storm-control row."),
    ("nganjirr", "noun", None, "NA", "grass tree", "batch-197: grass tree only; no burning/ritual-use row."),
    ("junda", "noun", None, "NA", "wild plum", "batch-197: wild plum only; no gathering/eating/fig drift row."),
    ("jikan", "noun", None, "NA", "grass", "batch-197: grass only; no walking-through/snake/feed/burning frame."),
    ("buyku", "noun", None, "NA", "paperbark", "batch-197: paperbark only; no cover/roof/carrier/bark-use row."),
    ("kanunjul", "noun", None, "NA", "grass-tree resin", "batch-197: grass-tree resin only; no burning/storm-control row."),
    ("yibuy", "noun", None, "NA", "loya cane", "batch-197: loya cane only; no weaving/tying/walking-stick/material-source row."),
    ("wukay", "noun", None, "NA", "hairy yam", "batch-197: hairy yam only; no digging/eating/cooking/searching row."),
    ("yinyay", "demonstrative", None, "NA", "there", "batch-197: retained local demonstrative in deictic identification rows."),
    ("yaluy", "demonstrative", None, "NA", "here", "batch-197: retained local demonstrative in perception rows."),
    ("nyaji-l", "verb", "l", "NA", "see; perceive", "batch-197: retained past and nonpast perception rows with plant-resource objects."),
    ("ngayu", "pronoun", None, "NA", "I; 1sg nominative", "batch-197: bare pronoun A in perception rows."),
    ("yundu", "pronoun", None, "NA", "you; 2sg nominative", "batch-197: bare pronoun A in perception rows."),
    ("jana", "pronoun", None, "NA", "they; 3pl nominative", "batch-197: bare pronoun A in past perception rows."),
    ("ngamu", "noun", None, "NA", "mother", "batch-197: common-noun A in perception rows, ERG-marked."),
]


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-197-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 155 rows. Morphology checked bare plant-resource targets, no target case/compound forms, yinyay/yaluy support only, common-noun A ERG, pronoun A bare, nyaji-ny past, and nyaji-l nonpast. Lexicon checked selected plant-resource senses. Syntax checked deictic identification, present perception, past perception, second-person perception, and ngamu-ngku perception. Fidelity checked no plant-use/medicine/material-source/weather 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 digging/eating/gathering/burning/scraping/chopping/weaving/tying/cooking row, no medicine/resin/bark-use/material-source row, and no carry-forward weather/geography/implement semantics.",
                 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 155 lessons covering process, lexical senses, morphology, syntax, fidelity, register, and handoff.",
                 artifact_path="batch_scripts/close_197.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 155 targets, support forms, participants, and perception.",
                 artifact_path="batch_scripts/close_197.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 197: 50 accepted Rule 155 plant-resource lexical-expansion rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
                 command="python3 batch_scripts/close_197.py", artifact_path="batch_scripts/close_197.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-197:%'").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())
