"""look_at_image 的问题收敛与兼容兜底测试（不碰网络和数据库）。"""
from __future__ import annotations

import unittest
import uuid
from pathlib import Path
from unittest import mock

from core.ark_client import ArkConfig
from tools.look_at_image import LookAtImageTool, _DEFAULT_QUESTION


class LookAtImageQuestionTests(unittest.TestCase):
    def _tool(self) -> LookAtImageTool:
        return LookAtImageTool(
            ark_cfg=ArkConfig(api_key="test", base_url="https://example.invalid", raw={}),
            vision_variant_cfg={
                "model_id": "vision-test",
                "request_timeout_s": 1,
                "timeout_retries": 0,
            },
            variant_key="test",
            working_dir=Path("."),
            task_id=uuid.uuid4(),
            user_id=uuid.uuid4(),
            base_dir=Path("."),
            user_root=Path("."),
        )

    def _execute_and_question(self, question=None) -> str:
        captured = {}

        def fake_chat(_cfg, _endpoint, body, **_kwargs):
            captured["question"] = body["messages"][0]["content"][0]["text"]
            return {
                "choices": [{"finish_reason": "stop", "message": {"content": "ok"}}],
                "usage": {},
            }, ""

        with mock.patch(
            "tools.look_at_image.load_image_as_data_url",
            return_value=("data:image/png;base64,AA==", "image.png", ""),
        ), mock.patch("tools.look_at_image.ark_chat_with_retry", side_effect=fake_chat), \
             mock.patch("tools.look_at_image.record_usage_safe", return_value=0):
            self._tool().execute("image.png", question=question)
        return captured["question"]

    def test_specific_question_is_forwarded_unchanged(self):
        question = "只读出仪表盘当前数值，不要描述其他内容。"
        self.assertEqual(self._execute_and_question(question), question)

    def test_missing_question_uses_concise_compatibility_fallback(self):
        self.assertEqual(self._execute_and_question(), _DEFAULT_QUESTION)
        self.assertIn("简洁", _DEFAULT_QUESTION)
        self.assertIn("不要主动全文 OCR", _DEFAULT_QUESTION)
        self.assertNotIn("完整描述画面内容", _DEFAULT_QUESTION)
        self.assertNotIn("把其中的数据、坐标轴、图例", _DEFAULT_QUESTION)


if __name__ == "__main__":
    unittest.main()
