"""JSONL metrics recorder for cross-session observability.

Process-global, thread-safe. Silent by default — opt-in via
``TOKENMOULDS_METRICS_PATH`` environment variable.

See ADR 019, item 12.
"""

from __future__ import annotations

import json
import threading
import time
from pathlib import Path
from typing import Any


_lock = threading.Lock()
_buffer: list[dict[str, Any]] = []
_file_path: Path | None = None
_initialised = False


def _ensure_init() -> None:
    global _file_path, _initialised
    if _initialised:
        return
    from tokenmoulds.settings import get_settings

    settings = get_settings()
    _file_path = settings.metrics_path
    _initialised = True


def record_metric(
    name: str,
    payload: dict[str, Any] | None = None,
    *,
    tags: dict[str, str] | None = None,
) -> None:
    """Record a metric event.

    Always buffers in-memory. Appends JSONL to disk when
    ``TOKENMOULDS_METRICS_PATH`` is set.
    """
    entry: dict[str, Any] = {
        "name": name,
        "ts": time.time(),
    }
    if payload:
        entry["payload"] = payload
    if tags:
        entry["tags"] = tags

    with _lock:
        _ensure_init()
        _buffer.append(entry)
        if _file_path is not None:
            _file_path.parent.mkdir(parents=True, exist_ok=True)
            with _file_path.open("a", encoding="utf-8") as f:
                f.write(json.dumps(entry) + "\n")


def get_buffered_metrics() -> list[dict[str, Any]]:
    """Return all buffered metrics (for test introspection)."""
    with _lock:
        return list(_buffer)


def clear_metrics() -> None:
    """Clear the in-memory buffer and reset init state."""
    global _buffer, _initialised, _file_path
    with _lock:
        _buffer.clear()
        _initialised = False
        _file_path = None
