"""SL9 evolution.jsonl — 统一 action 形状。"""

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

SL9_ACTIONS = frozenset(
    {
        "reflect_adopt",
        "vault_adopt",
        "config_self",
        "promote_subject",
        "correct_mark_hypothesis",
        "correct_restore_baseline",
        "correct_patch_narrative",
        "cultural_batch",
        "web_learning_batch",
        "core_correct",
    }
)


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def append_evolution(
    log_path: Path,
    *,
    action: str,
    actor: str = "system",
    target: dict[str, Any] | None = None,
    detail: dict[str, Any] | str | None = None,
    reviewer: str | None = None,
) -> dict[str, Any]:
    row: dict[str, Any] = {
        "at": _now_iso(),
        "action": action,
        "actor": actor,
    }
    if target:
        row["target"] = target
    if detail is not None:
        row["detail"] = detail
    if reviewer:
        row["reviewer"] = reviewer
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with log_path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(row, ensure_ascii=False) + "\n")
    return row
