"""Unit tests for _atomic_write_json in mcp_vm_blackbox._helpers."""

from __future__ import annotations

import json
from typing import TYPE_CHECKING

from mcp_vm_blackbox._helpers import _atomic_write_json

if TYPE_CHECKING:
    from pathlib import Path


# ---------------------------------------------------------------------------
# _atomic_write_json
# ---------------------------------------------------------------------------


def test_atomic_write_json_dict(tmp_path: Path) -> None:
    """Write a dict payload, read back, assert equality."""
    target = tmp_path / "out.json"
    payload = {"key": "value", "nested": {"a": 1}}
    _atomic_write_json(target, payload)
    assert json.loads(target.read_text()) == payload


def test_atomic_write_json_list(tmp_path: Path) -> None:
    """Write a list-of-dicts payload, read back, assert equality."""
    target = tmp_path / "out.json"
    payload = [{"id": 1, "name": "alpha"}, {"id": 2, "name": "beta"}]
    _atomic_write_json(target, payload)
    assert json.loads(target.read_text()) == payload


def test_atomic_write_json_overwrites(tmp_path: Path) -> None:
    """Writing twice to the same path keeps only the latest content."""
    target = tmp_path / "out.json"
    _atomic_write_json(target, {"version": 1})
    _atomic_write_json(target, {"version": 2})
    assert json.loads(target.read_text()) == {"version": 2}


def test_atomic_write_json_creates_parent_dirs(tmp_path: Path) -> None:
    """Writing to a nested non-existent path creates parent directories."""
    target = tmp_path / "deep" / "nested" / "dir" / "out.json"
    payload = {"created": True}
    _atomic_write_json(target, payload)
    assert json.loads(target.read_text()) == payload
