#!/usr/bin/env python3
"""Retrospectively backfill structured process events for pre-ledger batches."""
from __future__ import annotations

import datetime as dt
import hashlib
import sqlite3
from pathlib import Path

from process_ledger import ensure_schema, record_event

ROOT = Path("/mnt/donto-data/donto-resources/research/translation-training/kuku-yalanji-runpod-2026-06-30")
SYNTH = ROOT / "synthetic/claude-synthetic-v1-2026-07-02"
DB = SYNTH / "synthetic.db"
COMBINED_LOG = "process_logs/retrospective-process-backfill-batches-125-140.md"
NOW = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
LENSES = {"morphology", "lexicon", "syntax", "fidelity", "register"}


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def artifact_for(number: int) -> str:
    matches = sorted((SYNTH / "process_logs").glob(f"batch-{number}-*process.md"))
    if len(matches) > 1:
        raise SystemExit(f"batch-{number}: ambiguous process logs")
    return str(matches[0].relative_to(SYNTH)) if matches else COMBINED_LOG


def main() -> int:
    db = sqlite3.connect(DB)
    db.execute("PRAGMA foreign_keys=ON")
    db.execute("BEGIN")
    ensure_schema(db)
    for number in range(125, 141):
        label = f"batch-{number}"
        batch = db.execute("SELECT id,cheatsheet_version FROM batches WHERE label=?", (label,)).fetchone()
        if not batch:
            raise SystemExit(f"{label}: missing")
        bid, rule = batch
        status = dict(db.execute("SELECT status,COUNT(*) FROM sentences WHERE batch_id=? GROUP BY status", (bid,)))
        lens_counts = dict(
            db.execute(
                """SELECT r.lens,COUNT(*) FROM reviews r JOIN sentences s ON s.id=r.sentence_id
                     WHERE s.batch_id=? AND r.verdict='pass' GROUP BY r.lens""",
                (bid,),
            )
        )
        lessons = db.execute("SELECT COUNT(*) FROM lessons WHERE batch_id=?", (bid,)).fetchone()[0]
        lexeme_logs = db.execute("SELECT COUNT(*) FROM lexeme_log WHERE action LIKE ?", (label + "%",)).fetchone()[0]
        cumulative = db.execute(
            """SELECT COUNT(*) FROM sentences s JOIN batches b ON b.id=s.batch_id
                WHERE b.id<=? AND s.status IN ('accepted','revised')""",
            (bid,),
        ).fetchone()[0]
        if status != {"accepted": 50} and status != {"revised": 50} and sum(status.get(x, 0) for x in ("accepted", "revised")) != 50:
            raise SystemExit(f"{label}: status {status}")
        if set(lens_counts) != LENSES or any(count != 50 for count in lens_counts.values()):
            raise SystemExit(f"{label}: lenses {lens_counts}")
        if lessons == 0 or lexeme_logs == 0:
            raise SystemExit(f"{label}: lessons/logs {lessons}/{lexeme_logs}")
        if db.execute("SELECT COUNT(*) FROM process_events WHERE batch_label=?", (label,)).fetchone()[0]:
            raise SystemExit(f"{label}: events already exist")
        bank = SYNTH / "batch_scripts" / f"bank_{number}.py"
        close = SYNTH / "batch_scripts" / f"close_{number}.py"
        artifact = artifact_for(number)
        record_event(
            db,
            batch_label=label,
            phase="retrospective-audit",
            event_type="retrospective-process-backfill",
            actor="codex",
            detail=(
                f"Reconstructed 2026-07-10 from authoritative artifacts; not a contemporaneous timestamp. "
                f"{rule}; rows=50; status={status}; cumulative={cumulative}; "
                f"bank_sha256={sha(bank)}; close_sha256={sha(close)}."
            ),
            artifact_path=artifact,
            created_at=NOW,
        )
        record_event(
            db,
            batch_label=label,
            phase="retrospective-audit",
            event_type="retrospective-quality-evidence",
            actor="codex",
            detail=(
                f"Reconstructed evidence: five lenses 50/50 each (250 pass); lessons={lessons}; "
                f"batch-labelled lexeme logs={lexeme_logs}; accepted/revised rows=50; no open/rejected row."
            ),
            artifact_path=artifact,
            created_at=NOW,
        )
    db.commit()
    print("retrospective process events backfilled: batches 125-140, 32 events")
    return 0


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