"""宿主机工作区切换调试日志（JSON Lines）。"""

from __future__ import annotations

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

from config import LOGS_DIR

_LOG_FILE = Path(LOGS_DIR).expanduser().resolve() / "host_workspace_debug.log"
_LOCK = threading.Lock()


def write_host_workspace_debug(event: str, **payload: Any) -> None:
    """写入一条宿主机工作区调试日志。"""
    try:
        record = {
            "ts": datetime.now().isoformat(),
            "event": event,
            **payload,
        }
        line = json.dumps(record, ensure_ascii=False, default=str)
        with _LOCK:
            _LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
            with _LOG_FILE.open("a", encoding="utf-8") as fp:
                fp.write(line + "\n")
    except Exception:
        # 调试日志不应影响主流程
        return


def get_host_workspace_debug_log_path() -> str:
    return str(_LOG_FILE)

