from __future__ import annotations

import json
from pathlib import Path

import pytest

from csv_to_json import convert, read_rows


def test_quoted_fields_and_crlf_are_preserved(tmp_path: Path) -> None:
    source = tmp_path / "input.csv"
    output = tmp_path / "output.json"
    source.write_text('id,name,note\r\n1,Ada,"hello, world"\r\n2,Grace,"said ""hi"""\r\n', encoding="utf-8")

    rows, fields = convert(source, output)

    assert rows == 2
    assert fields == ["id", "name", "note"]
    assert json.loads(output.read_text(encoding="utf-8")) == [
        {"id": "1", "name": "Ada", "note": "hello, world"},
        {"id": "2", "name": "Grace", "note": 'said "hi"'},
    ]


@pytest.mark.parametrize(
    "text, message",
    [
        ("id,id\n1,2\n", "unique"),
        ("id,\n1,2\n", "non-empty"),
        ("id,name\n1\n", "expected 2"),
        ("id,name\n1,\"unterminated\n", "valid CSV"),
    ],
)
def test_malformed_input_fails_closed(tmp_path: Path, text: str, message: str) -> None:
    source = tmp_path / "bad.csv"
    source.write_text(text, encoding="utf-8")

    with pytest.raises(ValueError, match=message):
        read_rows(source)
