"""Tests for highlight extraction across backends."""

from __future__ import annotations

import pytest

from search.backends.memory import MemoryBackend
from search.models import (
    IndexConfig,
    SearchDocument,
    SearchQuery,
)


@pytest.fixture()
async def backend() -> MemoryBackend:
    b = MemoryBackend()
    await b.create_index(
        IndexConfig(name="docs", searchable_fields=["title", "body"])
    )
    await b.bulk_index([
        SearchDocument(
            id="1",
            content={"title": "Python Programming", "body": "Learn Python with examples"},
            index_name="docs",
        ),
        SearchDocument(
            id="2",
            content={"title": "Rust Language", "body": "Systems programming in Rust"},
            index_name="docs",
        ),
        SearchDocument(
            id="3",
            content={"title": "Full-Stack Guide", "body": "Build apps with Python and React"},
            index_name="docs",
        ),
    ])
    return b


class TestHighlights:
    async def test_highlights_contain_em_tags(self, backend: MemoryBackend):
        result = await backend.search("docs", SearchQuery(query="Python"))
        for r in result.results:
            assert any("<em>" in v for v in r.highlights.values())

    async def test_highlight_in_correct_field(self, backend: MemoryBackend):
        result = await backend.search("docs", SearchQuery(query="Python"))
        for r in result.results:
            for field, snippet in r.highlights.items():
                assert "<em>" in snippet

    async def test_no_highlights_when_disabled(self, backend: MemoryBackend):
        result = await backend.search(
            "docs", SearchQuery(query="Python", highlight=False)
        )
        for r in result.results:
            assert r.highlights == {}

    async def test_no_highlights_for_empty_query(self, backend: MemoryBackend):
        result = await backend.search("docs", SearchQuery(query=""))
        for r in result.results:
            assert r.highlights == {}

    async def test_highlight_preserves_case(self, backend: MemoryBackend):
        result = await backend.search("docs", SearchQuery(query="python"))
        found_highlight = False
        for r in result.results:
            for snippet in r.highlights.values():
                if "<em>Python</em>" in snippet:
                    found_highlight = True
        assert found_highlight

    async def test_multi_term_highlights(self, backend: MemoryBackend):
        result = await backend.search("docs", SearchQuery(query="Python React"))
        # Doc 3 has both terms
        doc3_results = [r for r in result.results if r.id == "3"]
        assert len(doc3_results) == 1
        assert doc3_results[0].highlights  # should have highlights
