"""Tests for the public ``mgf.common.io`` surface (atomic_write promotion)."""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.common import io as public_io
from mgf.common._io import atomic_write as _private_impl

if TYPE_CHECKING:
    from pathlib import Path


def test_public_atomic_write_is_the_private_impl() -> None:
    # The public module is a thin re-export — same object, no behaviour fork.
    assert public_io.atomic_write is _private_impl
    assert public_io.__all__ == ["atomic_write"]


def test_atomic_write_str_round_trip(tmp_path: Path) -> None:
    p = tmp_path / "f.txt"
    public_io.atomic_write(p, "hello", mode=0o600)
    assert p.read_text() == "hello"
    assert (p.stat().st_mode & 0o777) == 0o600


def test_atomic_write_bytes_round_trip(tmp_path: Path) -> None:
    p = tmp_path / "b.bin"
    public_io.atomic_write(p, b"\x00\x01\x02")
    assert p.read_bytes() == b"\x00\x01\x02"


def test_atomic_write_overwrites_atomically(tmp_path: Path) -> None:
    p = tmp_path / "f.txt"
    public_io.atomic_write(p, "v1")
    public_io.atomic_write(p, "v2")
    assert p.read_text() == "v2"
    # no leftover tempfiles in the dir
    assert [c.name for c in tmp_path.iterdir()] == ["f.txt"]
