"""Formato de las salidas: 10 decimales, sin ceros negativos, LF y UTF-8 sin BOM."""

import hashlib

import pytest
from estudio01 import report


@pytest.mark.parametrize(
    ("value", "text"),
    [
        (1.0 / 3.0, "0.3333333333"),
        (2.0 / 3.0, "0.6666666667"),
        (123.456, "123.4560000000"),
        (-0.0, "0.0000000000"),
        (-1e-18, "0.0000000000"),  # un negativo que redondea a cero no lleva signo
        (0.0, "0.0000000000"),
        (-0.5, "-0.5000000000"),
        (1e-10, "0.0000000001"),
    ],
)
def test_fmt_rounds_to_ten_decimals(value, text):
    assert report.fmt(value) == text


def test_booleans_are_written_as_true_and_false():
    assert (report.fmt_bool(True), report.fmt_bool(False)) == ("true", "false")


def test_csv_files_use_lf_and_utf8_without_bom(tmp_path):
    path = tmp_path / "x.csv"
    report.write_csv(path, ("a", "DSR ≥ 0.95"), [("1", "true"), (2, "false")])
    raw = path.read_bytes()
    assert raw == "a,DSR ≥ 0.95\n1,true\n2,false\n".encode()
    assert not raw.startswith(b"\xef\xbb\xbf")
    assert b"\r" not in raw


def test_json_is_sorted_indented_and_ends_with_one_newline(tmp_path):
    path = tmp_path / "x.json"
    report.write_json(path, {"b": 1, "a": {"y": 2, "x": 1}})
    text = path.read_text(encoding="utf-8")
    assert text == '{\n  "a": {\n    "x": 1,\n    "y": 2\n  },\n  "b": 1\n}\n'
    assert report.sha256_of(path) == hashlib.sha256(text.encode()).hexdigest()


@pytest.mark.parametrize("value", [float("nan"), float("inf"), float("-inf")])
def test_non_finite_values_stop_the_code_instead_of_being_written(value):
    with pytest.raises(ValueError, match="no finito"):
        report.fmt(value)
