from unittest.mock import MagicMock, patch
import pytest
from src import ai_client

@pytest.fixture(autouse=True)
def _reset_qwen_state():
 if hasattr(ai_client, '_qwen_client'):
  ai_client._qwen_client = None
 if hasattr(ai_client, '_qwen_history'):
  ai_client._qwen_history = []
 yield

def test_send_qwen_routes_to_dashscope(monkeypatch: pytest.MonkeyPatch) -> None:
 ai_client.set_provider("qwen", "qwen-max")
 with patch("src.ai_client._ensure_qwen_client") as ensure, \
  patch("src.ai_client._dashscope_call", return_value={"text": "hi from qwen", "tool_calls": [], "usage": {"input_tokens": 10, "output_tokens": 5}}) as call:
  result = ai_client._send_qwen("system", "user", ".", None, "", False, None, None, None)
  assert result == "hi from qwen"
  call.assert_called_once()
  ensure.assert_called_once()

def test_qwen_vision_vl_model_accepts_image(monkeypatch: pytest.MonkeyPatch) -> None:
 ai_client.set_provider("qwen", "qwen-vl-max")
 with patch("src.ai_client._ensure_qwen_client"), \
  patch("src.ai_client._dashscope_call", return_value={"text": "I see a cat", "tool_calls": [], "usage": {"input_tokens": 10, "output_tokens": 5}}) as call:
  file_items = [{"path": "/tmp/cat.png", "is_image": True, "base64_data": "iVBOR..."}]
  result = ai_client._send_qwen("system", "describe this image", ".", file_items, "", False, None, None, None)
  assert "cat" in result.lower()
  kwargs = call.call_args.kwargs
  msgs_str = str(kwargs.get("messages", [])).lower()
  assert "image" in msgs_str or "cat.png" in msgs_str

def test_qwen_tool_format_translation() -> None:
 from src.qwen_adapter import build_dashscope_tools
 openai_tools = [{"type": "function", "function": {"name": "read_file", "description": "Read a file", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}}]
 ds_tools = build_dashscope_tools(openai_tools)
 assert len(ds_tools) == 1
 assert ds_tools[0]["name"] == "read_file"
 assert "parameters" in ds_tools[0]

def test_qwen_error_classification() -> None:
 from src.result_types import ErrorKind
 from src.qwen_adapter import classify_dashscope_error
 from dashscope.common.error import AuthenticationError
 err = classify_dashscope_error(AuthenticationError("bad key"))
 assert err.kind == ErrorKind.AUTH
 assert err.source == "qwen_adapter"

def test_list_qwen_models_returns_hardcoded_registry() -> None:
 from src.ai_client import _list_qwen_models
 models = _list_qwen_models()
 assert "qwen-max" in models
 assert "qwen-vl-max" in models
 assert "qwen-turbo" in models
 assert "qwen-audio" in models
