"""Recall trace 采样落盘。"""

from __future__ import annotations

import json
import random
from pathlib import Path
from typing import Any


def maybe_write_recall_trace(
    home: Path,
    *,
    pack: Any,
    policy: str,
    sample_rate: float,
) -> None:
    if sample_rate <= 0:
        return
    if random.random() > sample_rate:
        return
    layers = getattr(pack, "layers", None) or {}
    row = {
        "policy": policy,
        "layer_counts": {k: len(v) if isinstance(v, list) else 0 for k, v in layers.items()},
        "trace_len": len(getattr(pack, "recall_trace", None) or []),
    }
    path = home / "sync" / "recall_traces.jsonl"
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(row, ensure_ascii=False) + "\n")
