"""Boundary tests for atomic_write SSOT — Law 11."""
import json
import tempfile
from pathlib import Path

from recoil.core.atomic_write import atomic_write_json, jsonl_append_locked


def test_atomic_write_json_creates_file_with_content():
    with tempfile.TemporaryDirectory() as td:
        target = Path(td) / "test.json"
        atomic_write_json(target, {"hello": "world"})
        assert json.loads(target.read_text()) == {"hello": "world"}


def test_atomic_write_json_overwrites_atomically():
    with tempfile.TemporaryDirectory() as td:
        target = Path(td) / "test.json"
        atomic_write_json(target, {"v": 1})
        atomic_write_json(target, {"v": 2})
        assert json.loads(target.read_text()) == {"v": 2}


def test_atomic_write_json_creates_parent_dirs():
    with tempfile.TemporaryDirectory() as td:
        target = Path(td) / "a" / "b" / "c" / "test.json"
        atomic_write_json(target, {"deep": True})
        assert target.exists()


def test_jsonl_append_locked_appends_lines():
    with tempfile.TemporaryDirectory() as td:
        target = Path(td) / "test.jsonl"
        jsonl_append_locked(target, {"a": 1})
        jsonl_append_locked(target, {"b": 2})
        lines = target.read_text().splitlines()
        assert json.loads(lines[0]) == {"a": 1}
        assert json.loads(lines[1]) == {"b": 2}
