import pytest

from fastapi_modules.fastapi_leaudit.services.impl.pageQualityServiceImpl import PageQualityServiceImpl


class _FakeVlmClient:
    def __init__(self, response):
        self.response = response
        self.prompts = []

    async def extract_multifield(self, *, prompt, images_data_urls, max_tokens=800):
        self.prompts.append((prompt, images_data_urls, max_tokens))
        if isinstance(self.response, Exception):
            raise self.response
        return self.response


@pytest.mark.asyncio
async def test_vlm_page_quality_reject_result_is_used():
    service = PageQualityServiceImpl()
    service.VlmClient = _FakeVlmClient(
        {
            "status": "reject",
            "score": 0.18,
            "reason": "页面文字严重模糊，无法稳定辨认关键内容",
        }
    )

    status, score, reason = await service._classify_page_image_by_vlm(b"image-bytes")

    assert status == "reject"
    assert score == 0.18
    assert "严重模糊" in reason
    assert "只输出 JSON" in service.VlmClient.prompts[0][0]


@pytest.mark.asyncio
async def test_vlm_page_quality_invalid_result_falls_back_to_review_not_pass():
    service = PageQualityServiceImpl()
    service.VlmClient = _FakeVlmClient({"status": "unknown", "reason": ""})

    status, score, reason = await service._classify_page_image_by_vlm(b"image-bytes")

    assert status == "review"
    assert score == 0.5
    assert "VLM返回结果不可用" in reason


@pytest.mark.asyncio
async def test_vlm_page_quality_error_falls_back_to_review_not_pass():
    service = PageQualityServiceImpl()
    service.VlmClient = _FakeVlmClient(RuntimeError("vlm down"))

    status, score, reason = await service._classify_page_image_by_vlm(b"image-bytes")

    assert status == "review"
    assert score == 0.5
    assert "VLM图片质量检测失败" in reason
