"""indexer モジュールのテスト."""

from pathlib import Path

from skill_search.indexer import SkillIndex, _split_into_sections, build_index
from skill_search.types import SkillMeta, SkillResource


class TestSplitIntoSections:
    """_split_into_sections のテスト."""

    def test_single_heading(self):
        text = """# Title

Some content here.

More content.
"""
        sections = _split_into_sections(text)
        assert len(sections) == 1
        assert sections[0][0] == "Title"
        assert "Some content here." in sections[0][1]

    def test_multiple_headings(self):
        text = """# First

Content 1.

## Second

Content 2.

### Third

Content 3.
"""
        sections = _split_into_sections(text)
        assert len(sections) == 3
        assert sections[0][0] == "First"
        assert sections[1][0] == "Second"
        assert sections[2][0] == "Third"

    def test_pre_heading_content(self):
        text = """Some preamble text.

# Title

Body content.
"""
        sections = _split_into_sections(text)
        assert len(sections) == 2
        assert sections[0][0] == ""  # 見出し前
        assert "preamble" in sections[0][1]
        assert sections[1][0] == "Title"

    def test_empty_text(self):
        sections = _split_into_sections("")
        assert sections == []

    def test_no_headings(self):
        text = "Just plain text without any headings."
        sections = _split_into_sections(text)
        assert len(sections) == 1
        assert sections[0][0] == ""
        assert "plain text" in sections[0][1]


class TestSkillIndex:
    """SkillIndex のテスト."""

    def test_add_and_search(self):
        index = SkillIndex()
        index.add_document(
            skill_name="test-skill",
            file_path="/path/SKILL.md",
            section="Introduction",
            content="This is a test skill for searching documents.",
        )
        index.add_document(
            skill_name="other-skill",
            file_path="/path/other/SKILL.md",
            section="Overview",
            content="A completely different skill about cooking recipes.",
        )
        index.commit()

        assert index.doc_count == 2

        # "test" で検索
        results = index.search("test searching documents", top_k=5)
        assert len(results) > 0
        assert results[0].skill_name == "test-skill"

    def test_search_with_skill_filter(self):
        index = SkillIndex()
        index.add_document(
            skill_name="alpha",
            file_path="/alpha/SKILL.md",
            section="API",
            content="Alpha API documentation for REST endpoints.",
        )
        index.add_document(
            skill_name="beta",
            file_path="/beta/SKILL.md",
            section="API",
            content="Beta API documentation for GraphQL endpoints.",
        )
        index.commit()

        # beta のみに限定した検索
        results = index.search("API documentation", skill_name="beta")
        assert all(r.skill_name == "beta" for r in results)

    def test_empty_index(self):
        index = SkillIndex()
        index.commit()
        results = index.search("anything")
        assert results == []

    def test_snippet_truncation(self):
        """長いコンテンツのスニペットが切り詰められる."""
        index = SkillIndex()
        long_content = "A" * 1000
        index.add_document(
            skill_name="long",
            file_path="/long/SKILL.md",
            section="Long",
            content=long_content,
        )
        index.commit()

        results = index.search("AAAA", top_k=1)
        if results:
            assert len(results[0].snippet) <= 503  # 500 + "..."


class TestBuildIndex:
    """build_index のテスト."""

    def test_build_from_skills(self, tmp_path: Path):
        # リソースファイルを作成
        resource_path = tmp_path / "resource.md"
        resource_path.write_text(
            "# API Reference\n\nEndpoint details here.", encoding="utf-8"
        )

        skills = [
            SkillMeta(
                name="test-skill",
                description="A test",
                path=str(tmp_path),
                content="# Test\n\nTest instructions.",
                resources=[
                    SkillResource(
                        name="resource.md",
                        path=str(resource_path),
                    )
                ],
            )
        ]

        index = build_index(skills)
        assert index.doc_count > 0

        # SKILL.md のコンテンツとリソースの両方が検索可能
        results_skill = index.search("Test instructions")
        assert len(results_skill) > 0

        results_resource = index.search("API Reference Endpoint")
        assert len(results_resource) > 0
