from types import SimpleNamespace

import pytest

from app.agents.tools.search import web_search


class FakeResult(SimpleNamespace):
    pass


def test_web_search_tool_formats_results(monkeypatch):
    class FakeService:
        async def search(self, query: str, limit: int | None = None):
            assert query == 'Jarvis 最新更新'
            assert limit == 2
            return [
                FakeResult(
                    title='Jarvis release notes',
                    url='https://example.com/jarvis-release',
                    snippet='Latest Jarvis changes.',
                    source='duckduckgo',
                    published_at='2026-03-29',
                )
            ]

    monkeypatch.setattr('app.services.web_search_service.WebSearchService', FakeService)

    result = web_search.func('Jarvis 最新更新', top_k=2)

    assert '[1] Jarvis release notes' in result
    assert '链接: https://example.com/jarvis-release' in result
    assert '来源: duckduckgo' in result
    assert '时间: 2026-03-29' in result
    assert '摘要: Latest Jarvis changes.' in result


def test_web_search_tool_returns_stable_message_when_unavailable(monkeypatch):
    from app.services.web_search_service import WebSearchConfigurationError

    class FakeService:
        async def search(self, query: str, limit: int | None = None):
            raise WebSearchConfigurationError('网页搜索未启用或未配置')

    monkeypatch.setattr('app.services.web_search_service.WebSearchService', FakeService)

    result = web_search.func('Jarvis')

    assert result == '网页搜索不可用: 网页搜索未启用或未配置'


@pytest.mark.asyncio
async def test_web_search_tool_runs_from_active_event_loop(monkeypatch):
    class FakeService:
        async def search(self, query: str, limit: int | None = None):
            assert query == 'Jarvis 最新更新'
            assert limit == 1
            return [
                FakeResult(
                    title='Jarvis release notes',
                    url='https://example.com/jarvis-release',
                    snippet='Latest Jarvis changes.',
                    source='duckduckgo',
                    published_at='2026-03-29',
                )
            ]

    monkeypatch.setattr('app.services.web_search_service.WebSearchService', FakeService)

    result = web_search.func('Jarvis 最新更新', top_k=1)

    assert '[1] Jarvis release notes' in result
    assert '链接: https://example.com/jarvis-release' in result
