from __future__ import annotations

import httpx
import pytest

from app.agent.web_search import WebSearchClient, _decode_ddg_redirect


@pytest.mark.asyncio
async def test_web_search_uses_duckduckgo_instant_answer():
    def handler(request: httpx.Request) -> httpx.Response:
        if "api.duckduckgo.com" in str(request.url):
            return httpx.Response(
                200,
                json={
                    "Heading": "HTML",
                    "AbstractText": "HyperText Markup Language",
                    "AbstractURL": "https://en.wikipedia.org/wiki/HTML",
                    "RelatedTopics": [],
                },
            )
        return httpx.Response(404, text="not found")

    transport = httpx.MockTransport(handler)
    async with httpx.AsyncClient(transport=transport) as client:
        search = WebSearchClient(client=client)
        result = await search.search(query="What is HTML", max_results=3)

    assert result["success"] is True
    assert result["provider"] == "duckduckgo"
    assert result["result_count"] >= 1
    assert result["results"][0]["title"] == "HTML"
    assert "HyperText Markup Language" in result["output"]


@pytest.mark.asyncio
async def test_web_search_requires_query():
    async with httpx.AsyncClient() as client:
        search = WebSearchClient(client=client)
        result = await search.search(query="  ")
    assert result["success"] is False
    assert result["error"] == "query is required"


def test_decode_ddg_redirect():
    raw = "//duckduckgo.com/l/?uddg=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FHTML&rut=abc"
    assert _decode_ddg_redirect(raw) == "https://en.wikipedia.org/wiki/HTML"
