from __future__ import annotations

from pathlib import Path

import pytest

from worai.core import profile_loader


class _Ctx:
    def __init__(self, obj: dict | None = None) -> None:
        self.obj = obj or {}


def test_resolve_profile_name_precedence(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("WORAI_PROFILE", "from-env")
    assert profile_loader.resolve_profile_name(_Ctx({"profile": "from-ctx"}), "explicit") == "explicit"
    assert profile_loader.resolve_profile_name(_Ctx({"profile": "from-ctx"}), None) == "from-ctx"
    assert profile_loader.resolve_profile_name(_Ctx({}), None) == "from-env"
    monkeypatch.delenv("WORAI_PROFILE", raising=False)
    assert profile_loader.resolve_profile_name(_Ctx({}), None) == "default"


def test_resolve_profile_config_path(monkeypatch: pytest.MonkeyPatch) -> None:
    assert profile_loader.resolve_profile_config_path(_Ctx({"config_path": "./a.toml"})).name == "a.toml"
    monkeypatch.setattr(profile_loader, "resolve_config_path", lambda _p: Path("/tmp/fallback.toml"))
    assert profile_loader.resolve_profile_config_path(None) == Path("/tmp/fallback.toml")


def test_load_profile_fails_when_sdk_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(profile_loader, "load_profile_config", None)
    with pytest.raises(ValueError, match="kg_build support is unavailable"):
        profile_loader.load_profile(None)


def test_load_profile_missing_profile(monkeypatch: pytest.MonkeyPatch) -> None:
    class _Config:
        @staticmethod
        def get(_name: str):
            return None

    monkeypatch.setattr(profile_loader, "load_profile_config", lambda _path: _Config())
    monkeypatch.setattr(profile_loader, "resolve_config_path", lambda _p: Path("/tmp/cfg.toml"))
    with pytest.raises(ValueError, match="Profile 'default' not found"):
        profile_loader.load_profile(None)


def test_load_profile_success_and_api_key_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
    class _Profile:
        api_key = "wl_profile"

    class _Config:
        @staticmethod
        def get(_name: str):
            return _Profile()

    monkeypatch.setattr(profile_loader, "load_profile_config", lambda _path: _Config())
    monkeypatch.setattr(profile_loader, "resolve_config_path", lambda _p: Path("/tmp/cfg.toml"))
    profile, name, path = profile_loader.load_profile(None)
    assert profile.api_key == "wl_profile"
    assert name == "default"
    assert path == Path("/tmp/cfg.toml")

    api_key, _, _ = profile_loader.resolve_profile_api_key(None)
    assert api_key == "wl_profile"

    class _NoKeyProfile:
        api_key = None

    class _NoKeyConfig:
        @staticmethod
        def get(_name: str):
            return _NoKeyProfile()

    monkeypatch.setattr(profile_loader, "load_profile_config", lambda _path: _NoKeyConfig())
    monkeypatch.setenv("WORDLIFT_API_KEY", "wl_env")
    api_key, _, _ = profile_loader.resolve_profile_api_key(None)
    assert api_key == "wl_env"
