from unittest.mock import MagicMock

from app.core.config import settings
from app.services import pricebot_llm_calls


def test_auth_probe_accepts_matching_secret(monkeypatch):
    monkeypatch.setattr(settings, "INTERNAL_API_SECRET", "same-secret")
    response = MagicMock(status_code=200)
    get = MagicMock(return_value=response)
    monkeypatch.setattr(pricebot_llm_calls.httpx, "get", get)

    assert pricebot_llm_calls.pricebot_llm_auth_ready() is True
    assert get.call_count == len(settings.pricebot_instances)
    assert all(
        call.kwargs["headers"]["X-Internal-Secret"] == "same-secret"
        for call in get.call_args_list
    )


def test_auth_probe_rejects_mismatched_secret(monkeypatch):
    monkeypatch.setattr(settings, "INTERNAL_API_SECRET", "app-server-secret")
    monkeypatch.setattr(
        pricebot_llm_calls.httpx,
        "get",
        MagicMock(return_value=MagicMock(status_code=403)),
    )

    assert pricebot_llm_calls.pricebot_llm_auth_ready() is False


def test_fetch_falls_back_to_other_instance_when_hash_target_is_empty(monkeypatch):
    monkeypatch.setattr(settings, "INTERNAL_API_SECRET", "same-secret")
    monkeypatch.setattr(
        settings,
        "PRICEBOT_INSTANCES",
        "http://pricebot-1:8000,http://pricebot-2:8000",
    )
    monkeypatch.setattr(
        pricebot_llm_calls,
        "pick_pricebot",
        lambda trace_id: "http://pricebot-1:8000",
    )
    calls = [{"model": "qwen", "usage": {"prompt_tokens": 1}}]

    def get(url, **kwargs):
        response = MagicMock(status_code=200)
        response.json.return_value = {
            "calls": [] if "pricebot-1" in url else calls
        }
        return response

    monkeypatch.setattr(pricebot_llm_calls.httpx, "get", get)

    assert pricebot_llm_calls.fetch_llm_calls("trace-after-rescale") == calls
