import csv
import json
from pathlib import Path

import pytest

from json_to_csv import convert


def write_json(path: Path, value: object) -> None:
    path.write_text(json.dumps(value), encoding="utf-8")


def test_union_of_keys_is_stable_and_missing_values_are_blank(tmp_path: Path) -> None:
    source = tmp_path / "rows.json"
    target = tmp_path / "rows.csv"
    write_json(source, [{"id": 1, "name": "Ada"}, {"id": 2, "active": True}])

    count, fields = convert(source, target)

    assert count == 2
    assert fields == ["id", "name", "active"]
    with target.open(newline="", encoding="utf-8") as handle:
        assert list(csv.DictReader(handle)) == [
            {"id": "1", "name": "Ada", "active": ""},
            {"id": "2", "name": "", "active": "True"},
        ]


@pytest.mark.parametrize("value", [[], {}, ["not an object"], [{"nested": {"x": 1}}]])
def test_invalid_shapes_are_rejected(tmp_path: Path, value: object) -> None:
    source = tmp_path / "bad.json"
    write_json(source, value)

    with pytest.raises(ValueError):
        convert(source, tmp_path / "out.csv")
