import json

import pytest

from scripts.msvc_harness.config import ConfigError, load_config


def _write_config(root, data):
    config_dir = root / ".harness"
    config_dir.mkdir()
    (config_dir / "config.json").write_text(
        json.dumps(data),
        encoding="utf-8",
    )


def test_load_config_uses_defaults(tmp_path):
    config = load_config(tmp_path)

    assert config.version == 1
    assert config.project_type == "auto"
    assert config.cmake.source_dir == tmp_path.resolve()
    assert config.cmake.binary_dir is None
    assert config.tdd.test_roots == (
        (tmp_path / "tests").resolve(),
        (tmp_path / "test").resolve(),
    )


def test_load_config_rejects_path_outside_repository(tmp_path):
    root = tmp_path / "repo"
    root.mkdir()
    _write_config(
        root,
        {
            "version": 1,
            "cmake": {
                "sourceDir": "../outside",
            },
        },
    )

    with pytest.raises(ConfigError, match="outside the repository"):
        load_config(root)


@pytest.mark.parametrize(
    "missing_field",
    ["binaryDir", "configurePreset", "buildPreset", "testPreset"],
)
def test_load_config_requires_all_cmake_preset_fields(tmp_path, missing_field):
    cmake = {
        "binaryDir": "out/build/windows-debug",
        "configurePreset": "windows-debug",
        "buildPreset": "windows-debug",
        "testPreset": "windows-debug",
    }
    del cmake[missing_field]
    _write_config(
        tmp_path,
        {
            "version": 1,
            "cmake": cmake,
        },
    )

    with pytest.raises(ConfigError, match="must be specified together"):
        load_config(tmp_path)
