from unittest.mock import patch


def test_provider_model_ids_prefers_curated_static_when_api_key_provider_catalog_fetch_fails(
    monkeypatch, tmp_path
):
    """API-key providers should fall back to curated static models, not just
    profile fallback aliases, when live /models discovery fails.

    Regression: DeepSeek auth/catalog failures collapsed the picker to the
    provider profile fallback_models tuple (chat + reasoner), hiding curated V4
    models that were already in ``_PROVIDER_MODELS['deepseek']``.
    """
    monkeypatch.setenv("HERMES_HOME", str(tmp_path))

    from hermes_cli.models import _PROVIDER_MODELS, clear_provider_models_cache, provider_model_ids

    clear_provider_models_cache("deepseek")
    expected = list(_PROVIDER_MODELS["deepseek"])

    with patch(
        "hermes_cli.auth.resolve_api_key_provider_credentials",
        return_value={
            "provider": "deepseek",
            "api_key": "sk-test",
            "base_url": "https://api.deepseek.com/v1",
            "source": "test",
        },
    ), patch("providers.base.ProviderProfile.fetch_models", return_value=None):
        result = provider_model_ids("deepseek")

    assert result == expected
    assert "deepseek-v4-pro" in result
    assert "deepseek-v4-flash" in result



def test_list_authenticated_providers_keeps_curated_models_when_live_catalog_fails(
    monkeypatch, tmp_path
):
    """The /model provider row should keep curated models on fetch failure.

    This exercises the picker path through cached_provider_model_ids() and
    list_authenticated_providers().
    """
    monkeypatch.setenv("HERMES_HOME", str(tmp_path))
    monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-test")

    from hermes_cli.models import _PROVIDER_MODELS, clear_provider_models_cache
    from hermes_cli.model_switch import list_authenticated_providers

    clear_provider_models_cache("deepseek")
    expected = list(_PROVIDER_MODELS["deepseek"])

    with patch("providers.base.ProviderProfile.fetch_models", return_value=None):
        providers = list_authenticated_providers(
            current_provider="openai-codex",
            current_base_url="https://chatgpt.com/backend-api/codex",
            current_model="gpt-5.4",
            max_models=20,
            refresh=True,
        )

    deepseek = next((p for p in providers if p["slug"] == "deepseek"), None)
    assert deepseek is not None
    assert deepseek["models"] == expected
    assert deepseek["total_models"] == len(expected)
    assert deepseek["models"][:2] == ["deepseek-v4-pro", "deepseek-v4-flash"]
