"""Tests for SWE-bench dataset loading, row filtering, and generation logic."""

from __future__ import annotations

import sys
import types

import pytest

from evals.swebench.generate import _load_dataset_rows


def _install_fake_datasets(monkeypatch, rows) -> None:
    fake_datasets = types.ModuleType("datasets")
    fake_datasets.load_dataset = lambda _dataset_name, split: rows[split]
    monkeypatch.setitem(sys.modules, "datasets", fake_datasets)


def test_load_dataset_rows_returns_unique_instance_rows(monkeypatch) -> None:
    _install_fake_datasets(
        monkeypatch,
        {
            "test": [
                {"instance_id": "i-1", "repo": "demo/a"},
                {"instance_id": "i-2", "repo": "demo/b"},
            ]
        },
    )

    rows = _load_dataset_rows(dataset_name="demo", split="test")

    assert sorted(rows) == ["i-1", "i-2"]
    assert rows["i-1"]["repo"] == "demo/a"
    assert rows["i-2"]["repo"] == "demo/b"


def test_load_dataset_rows_rejects_duplicate_instance_ids(monkeypatch) -> None:
    _install_fake_datasets(
        monkeypatch,
        {
            "test": [
                {"instance_id": "dupe-1", "repo": "demo/a"},
                {"instance_id": "dupe-1", "repo": "demo/b"},
            ]
        },
    )

    with pytest.raises(RuntimeError, match="Duplicate instance_id values found"):
        _load_dataset_rows(dataset_name="demo", split="test")
