#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AI recommendation route Ollama-first display contract."""


def _client(monkeypatch):
    from flask import Flask
    import auth
    from routes.ai_routes import ai_bp

    monkeypatch.setattr(auth, "DISABLE_LOGIN", True)
    app = Flask(__name__)
    app.secret_key = "test"
    app.register_blueprint(ai_bp)
    return app.test_client()


def test_initial_ai_status_sanitizes_cached_gemini_recommendation(monkeypatch):
    import routes.ai_routes as ai_routes

    monkeypatch.setattr(
        ai_routes.ai_provider_service,
        "_status_cache",
        {
            "data": {
                "default_provider": "gemini",
                "recommended_provider": "gemini",
                "ollama": {"connected": None},
                "gemini": {"connected": True},
            }
        },
    )

    status = ai_routes._get_ai_status_for_initial_render()

    assert status["default_provider"] == "ollama"
    assert status["recommended_provider"] == "ollama"

def test_initial_ai_status_never_recommends_gemini_without_cache(monkeypatch):
    import routes.ai_routes as ai_routes

    class FakeProvider:
        default_provider = "gemini"
        _status_cache = {}

    monkeypatch.setattr(ai_routes, "ai_provider_service", FakeProvider())

    status = ai_routes._get_ai_status_for_initial_render()

    assert status["default_provider"] == "ollama"
    assert status["recommended_provider"] == "ollama"

def test_set_provider_error_uses_ollama_primary_wording(monkeypatch):
    client = _client(monkeypatch)
    response = client.post("/api/ai/set_provider", json={"provider": "other"})

    assert response.status_code == 400
    assert response.get_json()["error"] == "無效的提供者，請使用 Ollama 主路徑"
