import json

import pytest

from cog_mcp.config import Config

REQUIRED_ENV = {
    "CDF_CLIENT_ID": "client-id",
    "CDF_TENANT_ID": "tenant-id",
    "CDF_CLUSTER": "westeurope-1",
    "CDF_PROJECT": "project-name",
    "CDF_CLIENT_SECRET": "secret",
    "CDF_DATA_MODELS": '[{"space": "model-space", "externalId": "Model", "version": "1"}]',
    "CDF_INSTANCE_SPACES": '["space-a", "space-b"]',
}


def _set_required_env(monkeypatch: pytest.MonkeyPatch) -> None:
    for key, value in REQUIRED_ENV.items():
        monkeypatch.setenv(key, value)


def test_from_env_parses_expected_values(monkeypatch: pytest.MonkeyPatch) -> None:
    _set_required_env(monkeypatch)

    config = Config.from_env()

    assert config.client_id == "client-id"
    assert config.tenant_id == "tenant-id"
    assert config.cluster == "westeurope-1"
    assert config.project == "project-name"
    assert config.client_secret == "secret"
    assert config.token_url is None
    assert len(config.data_models) == 1
    assert config.data_models[0].space == "model-space"
    assert config.data_models[0].external_id == "Model"
    assert config.data_models[0].version == "1"
    assert config.instance_spaces == ["space-a", "space-b"]


@pytest.mark.parametrize("missing_var", list(REQUIRED_ENV.keys()))
def test_from_env_reports_missing_required_vars(
    monkeypatch: pytest.MonkeyPatch, missing_var: str
) -> None:
    _set_required_env(monkeypatch)
    monkeypatch.delenv(missing_var, raising=False)

    with pytest.raises(ValueError, match=missing_var):
        Config.from_env()


def test_from_env_supports_optional_token_url(monkeypatch: pytest.MonkeyPatch) -> None:
    _set_required_env(monkeypatch)
    monkeypatch.setenv("CDF_TOKEN_URL", "https://login.example.com/token")

    config = Config.from_env()

    assert config.token_url == "https://login.example.com/token"


@pytest.mark.parametrize(
    ("var_name", "invalid_value"),
    [
        ("CDF_DATA_MODELS", "{not-json"),
        ("CDF_INSTANCE_SPACES", "[bad-json]"),
    ],
)
def test_from_env_raises_for_malformed_json(
    monkeypatch: pytest.MonkeyPatch, var_name: str, invalid_value: str
) -> None:
    _set_required_env(monkeypatch)
    monkeypatch.setenv(var_name, invalid_value)

    with pytest.raises(json.JSONDecodeError):
        Config.from_env()
