from __future__ import annotations

import json
from pathlib import Path

import pytest
import yaml

from omni.config.loader import load_config


def test_runtime_dict_precedence_over_paths(tmp_path: Path) -> None:
    path = tmp_path / "config.yml"
    path.write_text(
        yaml.safe_dump(
            {
                "default_instance": "file",
                "instances": {"file": {"url": "https://file.example"}},
            }
        ),
        encoding="utf-8",
    )

    cfg = load_config(
        {
            "default_instance": "runtime",
            "instances": {"runtime": {"url": "https://runtime.example"}},
        },
        config_path=path,
    )

    assert cfg.source == "runtime-dict"
    assert cfg.data.default_instance == "runtime"


def test_explicit_path_precedence_over_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    env_path = tmp_path / "env.json"
    env_path.write_text(
        json.dumps(
            {
                "default_instance": "env",
                "instances": {"env": {"url": "https://env.example"}},
            }
        ),
        encoding="utf-8",
    )

    explicit_path = tmp_path / "explicit.toml"
    explicit_path.write_text(
        'default_instance = "explicit"\n[instances.explicit]\nurl = "https://explicit.example"\n',
        encoding="utf-8",
    )

    monkeypatch.setenv("OMNI_SDK_CONFIG", str(env_path))
    cfg = load_config(config_path=explicit_path)

    assert cfg.source == "explicit-path"
    assert cfg.data.default_instance == "explicit"


def test_env_fallback(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    env_path = tmp_path / "env.yml"
    env_path.write_text(
        yaml.safe_dump(
            {
                "default_instance": "env",
                "instances": {"env": {"url": "https://env.example"}},
            }
        ),
        encoding="utf-8",
    )
    monkeypatch.setenv("OMNI_SDK_CONFIG", str(env_path))

    cfg = load_config()
    assert cfg.source.startswith("env:")
    assert cfg.data.default_instance == "env"
