"""Optional NDJSON agent debug logging (no-op unless enabled)."""

from __future__ import annotations

import json
import logging
import os
import time
from typing import Any

log = logging.getLogger("mcube.debug_ndjson")


def agent_debug_log(
    hypothesis_id: str,
    location: str,
    message: str,
    data: dict[str, Any] | None = None,
) -> None:
    """
    Structured debug hook used by ``ws_bridge`` (Cursor/agent instrumentation).

    Writes one NDJSON line to the path in ``MCUBE_AGENT_DEBUG_LOG`` when set; otherwise no-op.
    """
    path = (os.getenv("MCUBE_AGENT_DEBUG_LOG") or "").strip()
    if not path:
        return
    try:
        line = json.dumps(
            {
                "ts": time.time(),
                "hypothesisId": hypothesis_id,
                "location": location,
                "message": message,
                "data": data or {},
            },
            ensure_ascii=False,
            default=str,
        )
        with open(path, "a", encoding="utf-8") as f:
            f.write(line + "\n")
    except Exception:
        log.debug("agent_debug_log write failed", exc_info=True)
