# region TestService [TYPE Module]
# @RELATION  BELONGS_TO -> SrcRoot
# @SEMANTICS: tests, llm-analysis, fallback, provider-error, unknown-status
# @PURPOSE: Verify LLM analysis transport/provider failures do not masquerade as dashboard FAIL results.

import pytest

from src.plugins.llm_analysis.models import LLMProviderType
from src.plugins.llm_analysis.service import LLMClient


# region test_test_runtime_connection_uses_json_completion_transport [TYPE Function]
# @RELATION  BINDS_TO -> TestService
# @PURPOSE: Provider self-test must exercise the same chat completion transport as runtime analysis.
# @PRE  get_json_completion is available on initialized client.
# @POST  Self-test forwards a lightweight user message into get_json_completion and returns its payload.
@pytest.mark.anyio
async def test_test_runtime_connection_uses_json_completion_transport(monkeypatch):
    client = LLMClient(
        provider_type=LLMProviderType.OPENROUTER,
        api_key="sk-test-provider-key-123456",
        base_url="https://openrouter.ai/api/v1",
        default_model="nvidia/nemotron-nano-12b-v2-vl:free",
    )
    recorded = {}

    async def _fake_get_json_completion(messages):
        recorded["messages"] = messages
        return {"ok": True}

    monkeypatch.setattr(client, "get_json_completion", _fake_get_json_completion)

    result = await client.test_runtime_connection()

    assert result == {"ok": True}
    assert recorded["messages"][0]["role"] == "user"
    assert "Return exactly this JSON object" in recorded["messages"][0]["content"]
# endregion test_test_runtime_connection_uses_json_completion_transport


# region test_analyze_dashboard_provider_error_maps_to_unknown [TYPE Function]
# @RELATION  BINDS_TO -> TestService
# @PURPOSE: Infrastructure/provider failures must produce UNKNOWN analysis status rather than FAIL.
# @PRE  LLMClient.get_json_completion raises provider/auth exception.
# @POST  Returned payload uses status=UNKNOWN and issue severity UNKNOWN.
@pytest.mark.anyio
async def test_analyze_dashboard_provider_error_maps_to_unknown(monkeypatch, tmp_path):
    screenshot_path = tmp_path / "shot.jpg"
    screenshot_path.write_bytes(b"fake-image")

    client = LLMClient(
        provider_type=LLMProviderType.OPENROUTER,
        api_key="sk-test-provider-key-123456",
        base_url="https://openrouter.ai/api/v1",
        default_model="nvidia/nemotron-nano-12b-v2-vl:free",
    )

    async def _raise_provider_error(_messages):
        raise RuntimeError("Error code: 401 - {'error': {'message': 'User not found.', 'code': 401}}")

    monkeypatch.setattr(client, "get_json_completion", _raise_provider_error)

    result = await client.analyze_dashboard(str(screenshot_path), logs=["line-1"])

    assert result["status"] == "UNKNOWN"
    assert "Failed to get response from LLM" in result["summary"]
    assert result["issues"][0]["severity"] == "UNKNOWN"
# endregion test_analyze_dashboard_provider_error_maps_to_unknown
# endregion TestService
