from __future__ import annotations

import pytest

from youtube_cli_agent.errors import ToolExecutionError
from youtube_cli_agent.tools.search import YouTubeSearchTool


class FakeSearchBackend:
    def __init__(self, payload: list[dict]):
        self.payload = payload

    def search(self, query: str, limit: int) -> list[dict]:
        return self.payload


def test_search_tool_deterministic_ranking_and_deduplication() -> None:
    backend = FakeSearchBackend(
        [
            {"id": "a1", "title": "First", "channel": "C1", "url": "https://youtu.be/a1", "duration": 30},
            {"id": "a1", "title": "First Duplicate", "channel": "C1", "url": "https://youtu.be/a1", "duration": 30},
            {"id": "b2", "title": "Second", "channel": "C2", "url": "https://youtu.be/b2", "duration": 60},
            {"title": "Missing id"},
        ]
    )
    tool = YouTubeSearchTool(backend=backend)

    results = tool.run("webflow", limit=10)

    assert [item.video_id for item in results] == ["a1", "b2"]
    assert [item.rank for item in results] == [1, 2]


def test_search_tool_no_results() -> None:
    tool = YouTubeSearchTool(backend=FakeSearchBackend([]))
    with pytest.raises(ToolExecutionError) as exc:
        tool.run("nothing", limit=10)

    assert exc.value.code == "NO_SEARCH_RESULTS"
