from __future__ import annotations

import json
import logging
import time
from typing import Any, Dict

logger = logging.getLogger("telemetry")


def emit(name: str, **payload: Any) -> None:
    """Log structured telemetry as JSON."""
    if not name:
        return
    record = _safe_payload(payload)
    record.setdefault("event", name)
    record.setdefault("ts_ms", int(time.time() * 1000))
    try:
        logger.info(json.dumps(record, ensure_ascii=True, default=str))
    except Exception:  # noqa: BLE001
        logger.info("telemetry_fallback %s %s", name, record)


def track_event(event_name: str, properties: Dict[str, Any]) -> None:
    """
    Track an event with properties (alias for emit).

    Args:
        event_name: Name of the event (e.g., "contact_enrichment.scan")
        properties: Event properties/payload
    """
    emit(event_name, **properties)


def _safe_payload(payload: Dict[str, Any]) -> Dict[str, Any]:
    """Best-effort coercion to ensure payload logging never crashes."""
    safe: Dict[str, Any] = {}
    for key, value in payload.items():
        try:
            safe[key] = value
        except Exception:  # noqa: BLE001
            safe[key] = str(value)
    return safe
