#!/usr/bin/env python3
"""Close batch-146 after main-loop five-lens review."""

from __future__ import annotations

import datetime as dt
import json
import sqlite3
import sys

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-146"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
LENSES = ("morphology", "lexicon", "syntax", "fidelity", "register")

NOTES = (
    "CONSTRUCTION: ADJECTIVE SYNTAX, DEGREE, COMPARISON, AND PROPERTY CHANGE (Rule 104). 50 rows. DESIGN: "
    "follow the Rule 103 property lexicon with source-shaped constructions for adjective modifier order, "
    "inalienable and inanimate possessor phrases, jarra- degree, jarra- comparative with dative standards, "
    "-baja-ku high-degree marking, case insertion between -baja and -ku, and property/nominal inchoative and "
    "causative changes. SOURCE CONTROLS: Patz adjective inventory; NP modifier section; nominal/adjectival "
    "predicates; comparison dative section; degree section examples 78-85; inanimate possessor examples 524-526; "
    "state-change examples 314-324 and dayirr-bunga-l in ex.499. PROCESS STORAGE: source pass, risk controls, "
    "duplicate rejection, row inventory, lint outputs, five-lens review, close, export, and live-doc verification "
    "are stored in process_events and the batch process log."
)

LESSONS = [
    ("syntax", "Kuku Yalanji adjective modifiers normally follow the head noun; do not copy English pre-nominal adjective order.", "Rule 104: adjective-after-head modifier order."),
    ("syntax", "When a quantifier and adjective both modify a noun, Patz notes a tendency for the quantifier to precede the head while the adjective follows it.", "Rule 104: quantifier plus adjective NP order."),
    ("syntax", "Bare nominal/adjectival predicates need no copula: mayi ngulkurr and kalka dudu are complete predicate clauses.", "Rule 104: zero-copula nominal/adjectival predicates."),
    ("syntax", "Inalienable part constructions place whole and part in apposition; an adjective after the part modifies the part, not the whole.", "Rule 104: whole-part apposition."),
    ("syntax", "Inanimate possessors are commonly expressed by locative or ablative; marra-nga dandi is accepted for shell on zamia nut, but ablative was rejected there.", "Rule 104: inanimate possessor locative/ablative limits."),
    ("morphology", "`jarra-` before an adjective marks rather/fairly and also forms more-ADJ comparisons.", "Rule 104: jarra- degree/comparison."),
    ("syntax", "The standard of comparison is dative: karrkay-anka, ngujay-ngka, bulki-ka, minya-ka, bubu-ku.", "Rule 104: comparative dative."),
    ("morphology", "High degree is ADJ-baja-ku; bare `-baja` is incomplete for this adjective-degree construction.", "Rule 104: -baja-ku degree."),
    ("morphology", "If a -baja adjective also bears case, the case suffix goes between -baja and -ku: junkurr-ji-baja-ngka-ku, bambay-baja-nka-ku.", "Rule 104: -baja-CASE-ku slot."),
    ("orthography", "Source spelling may differ from the corpus norm: Patz has ngawuya, but this corpus normalizes the turtle word as ngawiya.", "Rule 104: source spelling normalization."),
    ("orthography", "Grammar analysis may show word-final -iy; elder-practical surface drops it, so jiba-badi-y surfaces as jiba-badi.", "Rule 104: final -iy surface discipline."),
    ("morphology", "Property inchoatives use -ma-l, with past surfaces such as ngulkurrman and duduman.", "Rule 104: property inchoatives."),
    ("morphology", "State causatives use -bunga-l or -kanga-l according to source and semantic class; do not freely invent causatives without a source-shaped frame.", "Rule 104: state causatives."),
    ("process", "Pre-bank duplicate scans matter for high-frequency grammar examples: Maral yinilman and Dubu-ngku maral yinil-kangan were rejected as exact Batch 129 duplicates.", "Rule 104 process: duplicate preflight."),
]

LEXEMES = [
    ("adjective-after-head", "construction", None, "NA", "noun followed by adjective modifier", "batch-146: default NP adjective order."),
    ("quantifier-plus-adjective-np", "construction", None, "NA", "quantifier plus noun plus adjective", "batch-146: wubul juku yalbay pattern."),
    ("zero-copula-adjective-predicate", "construction", None, "NA", "NP plus adjective predicate without copula", "batch-146: mayi ngulkurr / kalka dudu frame."),
    ("whole-part-apposition", "construction", None, "NA", "inalienable whole-part NP with optional adjective on the part", "batch-146: karrkay dukul yalbay."),
    ("inanimate-possessor-locative", "construction", None, "NA", "inanimate possessor expressed by locative", "batch-146: dumbul marra-nga dandi."),
    ("inanimate-possessor-ablative", "construction", None, "NA", "inanimate possessor/source expressed by ablative", "batch-146: yinya-muny juku-muny."),
    ("jarra-", "prefix", None, "NA", "rather; more in comparisons", "batch-146: degree and comparative prefix before adjectives."),
    ("comparative-dative", "construction", None, "NA", "standard of comparison takes dative case", "batch-146: jarra-ADJ plus dative standard."),
    ("-baja-ku", "suffix", None, "NA", "very; high degree on adjectives", "batch-146: adjective-baja-ku construction."),
    ("-baja-CASE-ku", "construction", None, "NA", "very with case inserted before emphatic -ku", "batch-146: junkurr-ji-baja-ngka-ku and bambay-baja-nka-ku."),
    ("property-inchoative", "construction", None, "NA", "adjective/noun plus -ma-l 'become X'", "batch-146: ngulkurr-ma-l, dudu-ma-l, nganka-ji-maniji-y."),
    ("state-causative", "construction", None, "NA", "nominal/adjectival base plus -bunga-l/-kanga-l 'make X'", "batch-146: dudu-bunga-l, manyarr-bunga-l, dayirr-bunga-l."),
    ("nuka-ji-y", "verb-itr", "y", "NA", "eat intransitively; be good to eat in property frame", "batch-146: Patz ex.525 good-to-eat frame."),
    ("nganka-ji-maniji-y", "verb-itr", "y", "NA", "get flowers; become flowerful", "batch-146: Patz ex.319 flame-tree inchoative."),
    ("manyarr-bunga-l", "verb-tr", "l", "NA", "cause to be wife; marry", "batch-146: Patz ex.323 nominal state causative."),
    ("dayirr-bunga-l", "verb-tr", "l", "NA", "make clean", "batch-146: Patz ex.499 clean causative."),
    ("dakwuy", "adjective", None, "NA", "hungry", "batch-146: degree example dakwuy-bajaku; grammar has dakuy spelling."),
    ("kingkin", "adjective", None, "NA", "cute", "batch-146: Patz ex.83 kingkin-bajaku."),
    ("ngujay", "noun", None, "potent", "freshwater turtle", "batch-146: comparison dative ngujay-ngka."),
    ("bulki", "noun", None, "neutral", "cattle; beef", "batch-146: comparison dative bulki-ka in beef comparison."),
    ("ngakun", "noun", None, "neutral", "flame tree", "batch-146: Patz ex.319 juku ngakun."),
    ("manyarr", "noun", None, "neutral", "wife", "batch-146: nominal state causative manyarr-bunga-l."),
]


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}")

    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-146-verify", note, 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 104 rows: morphology, lexicon, syntax, fidelity, and register. "
            "Special attention went to adjective-after-head order, jarra- degree/comparison, dative standards, "
            "-baja-ku with case-slot behavior, source spelling normalization, final -iy surface discipline, and "
            "property/nominal inchoative and causative frames."
        ),
        artifact_path="process_logs/batch-146-adjective-syntax-process.md",
        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 146: 50 accepted Rule 104 adjective-syntax rows, five-lens reviews, lessons, lexeme/source logs, and process evidence stored.",
        command="python3 batch_scripts/close_146.py",
        artifact_path="batch_scripts/close_146.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]
    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 action='batch-146-verify'").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, "
        f"{lesson_count} lessons, {lexeme_logs} lexeme/source-log rows, "
        f"{process_events} process events, verified corpus={verified}"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
