from pathlib import Path

from app import config as config_module
from app.services.llm_service import default_provider_capabilities, normalize_provider_name, resolve_provider_capabilities


def test_env_file_points_to_repo_root_env_file():
    assert config_module.ENV_FILE == Path(__file__).resolve().parents[4] / '.env'


def test_resolve_provider_capabilities_prefers_native_for_openai():
    capabilities = resolve_provider_capabilities({'provider': 'openai', 'model': 'gpt-4o', 'base_url': 'https://api.openai.com/v1'})

    assert capabilities.provider == 'openai'
    assert capabilities.supports_native_tools is True
    assert capabilities.preferred_tool_strategy == 'native'


def test_resolve_provider_capabilities_falls_back_for_openai_compatible_non_official_endpoint():
    capabilities = resolve_provider_capabilities(
        {'provider': 'openai', 'model': 'abab7.5-chat-preview', 'base_url': 'https://api.minimax.chat/v1'}
    )

    assert capabilities.provider == 'minimax'
    assert capabilities.supports_native_tools is False
    assert capabilities.preferred_tool_strategy == 'json_fallback'


def test_resolve_provider_capabilities_uses_global_openai_base_url_when_user_config_omits_it(monkeypatch):
    monkeypatch.setattr(config_module.settings, 'OPENAI_BASE_URL', 'https://api.minimax.chat/v1')

    capabilities = resolve_provider_capabilities({'provider': 'openai', 'model': 'abab7.5-chat-preview'})

    assert capabilities.provider == 'minimax'
    assert capabilities.supports_native_tools is False
    assert capabilities.preferred_tool_strategy == 'json_fallback'


def test_normalize_provider_name_recognizes_minimax_from_custom_config():
    assert normalize_provider_name({'provider': 'custom', 'model': 'MiniMax-M2.7-highspeed'}) == 'minimax'


def test_normalize_provider_name_recognizes_minimax_without_provider_when_base_url_matches():
    assert normalize_provider_name({'model': 'abab7.5-chat-preview', 'base_url': 'https://api.minimax.chat/v1'}) == 'minimax'


def test_resolve_provider_capabilities_falls_back_for_ollama():
    capabilities = resolve_provider_capabilities({'provider': 'ollama', 'model': 'qwen2.5'})

    assert capabilities.provider == 'ollama'
    assert capabilities.supports_native_tools is False
    assert capabilities.preferred_tool_strategy == 'json_fallback'


def test_default_provider_capabilities_follows_global_settings(monkeypatch):
    monkeypatch.setattr(config_module.settings, 'LLM_PROVIDER', 'ollama')

    capabilities = default_provider_capabilities()

    assert capabilities.provider == 'ollama'
    assert capabilities.preferred_tool_strategy == 'json_fallback'


def test_normalize_provider_name_without_provider_uses_global_default(monkeypatch):
    monkeypatch.setattr(config_module.settings, 'LLM_PROVIDER', 'ollama')

    assert normalize_provider_name({'model': 'qwen2.5'}) == 'ollama'
