"""Structured JSONL events for MCube pipeline debugging (STT / WS / TTS correlation)."""

from __future__ import annotations

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

_log = logging.getLogger("mcube.pipeline")

_lock = threading.Lock()


def _default_log_path() -> Path:
    base = os.getenv("MCUBE_LOG_DIR", "").strip() or "/tmp/mcube_logs"
    return Path(base) / "pipeline.jsonl"


def append_event(kind: str, **fields: Any) -> None:
    """
    Append one JSON line: {"ts": unix, "kind": str, ...}.
    Path: MCUBE_PIPELINE_LOG_PATH, else ${MCUBE_LOG_DIR:-/tmp/mcube_logs}/pipeline.jsonl.
    Set MCUBE_PIPELINE_LOG_DISABLE=1 to skip file I/O (still DEBUG-logs when enabled).
    """
    if os.getenv("MCUBE_PIPELINE_LOG_DISABLE", "").strip().lower() in ("1", "true", "yes"):
        return

    record: dict[str, Any] = {"ts": time.time(), "kind": kind}
    record.update(fields)

    line = json.dumps(record, default=str, ensure_ascii=False) + "\n"

    path_str = os.getenv("MCUBE_PIPELINE_LOG_PATH", "").strip()
    path = Path(path_str) if path_str else _default_log_path()

    if _log.isEnabledFor(logging.DEBUG):
        _log.debug("%s", line.strip())

    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        with _lock:
            with path.open("a", encoding="utf-8") as fh:
                fh.write(line)
    except OSError:
        pass
