from __future__ import annotations

import json
import os

import pytest

from ins_pricing.cli.utils.cli_config import build_env_map, load_config_json, set_env


def test_load_config_json_preflights_schema_errors(tmp_path):
    config_path = tmp_path / "invalid_config.json"
    config_path.write_text(
        json.dumps(
            {
                "data_dir": "./Data",
                "model_list": ["od"],
                "model_categories": ["bc"],
                "target": "y",
                "weight": "w",
                "feature_list": ["x1"],
                "categorical_features": [],
                "use_resn_data_parallel": True,
                "use_resn_ddp": True,
            }
        ),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="use_resn_data_parallel and use_resn_ddp"):
        load_config_json(
            config_path,
            required_keys=["data_dir", "model_list", "model_categories", "target", "weight"],
        )


def test_build_env_map_overrides_existing_values(monkeypatch):
    monkeypatch.setenv("OMP_NUM_THREADS", "2")

    env = build_env_map({"OMP_NUM_THREADS": "5"}, override=True)

    assert env["OMP_NUM_THREADS"] == "5"
    assert os.environ["OMP_NUM_THREADS"] == "2"


def test_set_env_can_preserve_existing_values(monkeypatch):
    monkeypatch.setenv("OMP_NUM_THREADS", "2")

    set_env({"OMP_NUM_THREADS": "5"}, override=False)

    assert os.environ["OMP_NUM_THREADS"] == "2"
