#!/usr/bin/env python3
"""Structured process-event ledger for the synthetic Kuku Yalanji corpus.

The sentence corpus already stores rows, reviews, revisions, lessons, and
lexeme logs. This helper adds a deliberately small append-only event table so
source checks, command results, and operator decisions can be queried later.
It never authors or edits Kuku sentence content.
"""

from __future__ import annotations

import argparse
import datetime as dt
import sqlite3

DB = "/mnt/donto-data/donto-resources/research/translation-training/kuku-yalanji-runpod-2026-06-30/synthetic/claude-synthetic-v1-2026-07-02/synthetic.db"


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def ensure_schema(db: sqlite3.Connection) -> None:
    db.execute(
        """
        CREATE TABLE IF NOT EXISTS process_events (
          id INTEGER PRIMARY KEY,
          batch_label TEXT NOT NULL,
          phase TEXT NOT NULL,
          event_type TEXT NOT NULL,
          actor TEXT NOT NULL,
          detail TEXT NOT NULL,
          command TEXT,
          output_excerpt TEXT,
          artifact_path TEXT,
          created_at TEXT NOT NULL
        )
        """
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_process_events_batch ON process_events(batch_label, created_at)"
    )
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_process_events_type ON process_events(event_type, created_at)"
    )


def record_event(
    db: sqlite3.Connection,
    *,
    batch_label: str,
    phase: str,
    event_type: str,
    actor: str,
    detail: str,
    command: str | None = None,
    output_excerpt: str | None = None,
    artifact_path: str | None = None,
    created_at: str | None = None,
) -> int:
    ensure_schema(db)
    cur = db.execute(
        """
        INSERT INTO process_events(
          batch_label, phase, event_type, actor, detail, command,
          output_excerpt, artifact_path, created_at
        )
        VALUES(?,?,?,?,?,?,?,?,?)
        """,
        (
            batch_label,
            phase,
            event_type,
            actor,
            detail,
            command,
            output_excerpt,
            artifact_path,
            created_at or utc_now(),
        ),
    )
    return int(cur.lastrowid)


def main() -> int:
    parser = argparse.ArgumentParser(description="Append a corpus process-event row.")
    parser.add_argument("--db", default=DB)
    parser.add_argument("--batch", required=True)
    parser.add_argument("--phase", required=True)
    parser.add_argument("--event-type", required=True)
    parser.add_argument("--actor", default="claude-main")
    parser.add_argument("--detail", required=True)
    parser.add_argument("--command")
    parser.add_argument("--output-excerpt")
    parser.add_argument("--artifact-path")
    args = parser.parse_args()

    db = sqlite3.connect(args.db)
    db.execute("BEGIN")
    event_id = record_event(
        db,
        batch_label=args.batch,
        phase=args.phase,
        event_type=args.event_type,
        actor=args.actor,
        detail=args.detail,
        command=args.command,
        output_excerpt=args.output_excerpt,
        artifact_path=args.artifact_path,
    )
    db.commit()
    print(f"recorded process_event {event_id} for {args.batch}")
    return 0


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