"""Tests for the dataset analyzer."""

from bilgeai.analyzer.dataset import _detect_format, analyze_dataset
from bilgeai.analyzer.models import DatasetProfile


class TestFormatDetection:
    def test_alpaca_format(self):
        assert _detect_format(["instruction", "input", "output"]) == "alpaca"

    def test_sharegpt_format(self):
        assert _detect_format(["conversations"]) == "sharegpt"

    def test_custom_format(self):
        assert _detect_format(["text", "label"]) == "custom"

    def test_empty_columns(self):
        assert _detect_format([]) == "unknown"


class TestDatasetAnalyzer:
    def test_analyze_alpaca_jsonl(self, sample_alpaca_jsonl):
        profile = analyze_dataset(sample_alpaca_jsonl)
        assert profile.format == "alpaca"
        assert profile.num_rows == 3
        assert profile.num_columns == 3
        assert "instruction" in profile.columns

    def test_analyze_sharegpt_jsonl(self, sample_sharegpt_jsonl):
        profile = analyze_dataset(sample_sharegpt_jsonl)
        assert profile.format == "sharegpt"
        assert profile.num_rows == 1

    def test_nonexistent_file(self, tmp_path):
        import pytest

        from bilgeai.core.exceptions import DataError

        with pytest.raises(DataError):
            analyze_dataset(tmp_path / "nonexistent.jsonl")

    def test_unsupported_format(self, tmp_path):
        import pytest

        from bilgeai.core.exceptions import DataError

        txt_file = tmp_path / "data.txt"
        txt_file.write_text("hello")
        with pytest.raises(DataError):
            analyze_dataset(txt_file)


class TestDatasetProfile:
    def test_serialization(self, small_dataset_profile):
        data = small_dataset_profile.model_dump()
        restored = DatasetProfile.model_validate(data)
        assert restored.num_rows == 500
        assert restored.format == "alpaca"
