"""Tests for ldf.docs module."""

from pathlib import Path

from ldf.docs import (
    _generate_footer,
    _generate_guardrails_section,
    _generate_mcp_section,
    _generate_packs_section,
    _generate_preset_section,
    export_docs,
)


class TestExportDocs:
    """Tests for export_docs function."""

    def test_exports_basic_docs(self, temp_project: Path):
        """Test exporting basic documentation."""
        result = export_docs(project_root=temp_project)

        assert "# test-project - LDF Framework Documentation" in result
        assert "LLM Development Framework" in result
        assert "## Project Preset" in result
        assert "## Active Guardrails" in result
        assert "## Question Packs" in result
        assert "## MCP Servers" in result

    def test_uses_cwd_when_no_root(self, temp_project: Path, monkeypatch):
        """Test using current working directory when project_root is None."""
        monkeypatch.chdir(temp_project)

        result = export_docs(project_root=None)

        assert "LDF Framework Documentation" in result

    def test_handles_missing_config(self, tmp_path: Path):
        """Test handling when config.yaml is missing."""
        ldf_dir = tmp_path / ".ldf"
        ldf_dir.mkdir()

        result = export_docs(project_root=tmp_path)

        # Should use directory name as project name
        assert tmp_path.name in result

    def test_includes_footer(self, temp_project: Path):
        """Test that footer is included."""
        result = export_docs(project_root=temp_project)

        assert "Generated by LDF" in result
        assert "github.com/LLMdotInfo/ldf" in result


class TestGeneratePresetSection:
    """Tests for _generate_preset_section function."""

    def test_generates_core_preset(self):
        """Test generating documentation for core preset."""
        config = {"guardrails": {"preset": "core"}}

        result = _generate_preset_section(config)

        assert "## Project Preset" in result
        assert "**Preset:** `core`" in result

    def test_generates_saas_preset(self):
        """Test generating documentation for saas preset."""
        config = {"guardrails": {"preset": "saas"}}

        result = _generate_preset_section(config)

        assert "`saas`" in result

    def test_handles_missing_preset(self):
        """Test handling when preset is not specified."""
        config = {}

        result = _generate_preset_section(config)

        assert "**Preset:** `custom`" in result

    def test_handles_unknown_preset(self):
        """Test handling unknown preset."""
        config = {"guardrails": {"preset": "unknown-preset"}}

        result = _generate_preset_section(config)

        assert "`unknown-preset`" in result


class TestGenerateGuardrailsSection:
    """Tests for _generate_guardrails_section function."""

    def test_generates_guardrails_list(self, temp_project: Path):
        """Test generating guardrails documentation."""
        result = _generate_guardrails_section(temp_project)

        assert "## Active Guardrails" in result
        assert "active guardrails" in result

    def test_includes_guardrail_details(self, temp_project: Path):
        """Test that guardrail details are included."""
        # Create guardrails.yaml with proper content
        guardrails_path = temp_project / ".ldf" / "guardrails.yaml"
        guardrails_path.write_text("""version: "1.0"
extends: core
""")

        result = _generate_guardrails_section(temp_project)

        # Should include guardrail content
        assert "## Active Guardrails" in result


class TestGeneratePacksSection:
    """Tests for _generate_packs_section function."""

    def test_generates_packs_list(self, temp_project: Path):
        """Test generating question packs documentation."""
        config = {"question_packs": ["core/security", "core/testing"]}
        ldf_dir = temp_project / ".ldf"

        result = _generate_packs_section(config, ldf_dir)

        assert "## Question Packs" in result
        assert "2" in result  # 2 packs

    def test_handles_empty_packs(self, temp_project: Path):
        """Test handling when no packs are configured."""
        config = {"question_packs": []}
        ldf_dir = temp_project / ".ldf"

        result = _generate_packs_section(config, ldf_dir)

        assert "**0** question packs" in result

    def test_includes_pack_questions(self, temp_project: Path):
        """Test including questions from pack file."""
        config = {"question_packs": ["test-pack"]}
        ldf_dir = temp_project / ".ldf"

        # Create a test pack file
        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "test-pack.yaml"
        pack_file.write_text("""name: test-pack
questions:
  general:
    - question: "What is the purpose?"
    - question: "How does it work?"
""")

        result = _generate_packs_section(config, ldf_dir)

        assert "test-pack" in result
        assert "Questions" in result

    def test_truncates_long_questions(self, temp_project: Path):
        """Test that long questions are truncated."""
        config = {"question_packs": ["test-pack"]}
        ldf_dir = temp_project / ".ldf"

        # Create a test pack with a very long question
        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "test-pack.yaml"
        long_question = "A" * 100
        pack_file.write_text(f"""name: test-pack
questions:
  general:
    - question: "{long_question}"
""")

        result = _generate_packs_section(config, ldf_dir)

        assert "..." in result  # Truncated

    def test_handles_flat_questions_list(self, temp_project: Path):
        """Test handling flat list of questions."""
        config = {"question_packs": ["test-pack"]}
        ldf_dir = temp_project / ".ldf"

        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "test-pack.yaml"
        pack_file.write_text("""name: test-pack
questions:
  - question: "Question 1"
  - question: "Question 2"
""")

        result = _generate_packs_section(config, ldf_dir)

        assert "Questions (2)" in result

    def test_handles_invalid_yaml(self, temp_project: Path):
        """Test handling invalid YAML in pack file."""
        config = {"question_packs": ["bad-pack"]}
        ldf_dir = temp_project / ".ldf"

        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "bad-pack.yaml"
        pack_file.write_text("invalid: yaml: content: [[[")

        # Should not raise an exception
        result = _generate_packs_section(config, ldf_dir)

        assert "bad-pack" in result

    def test_includes_short_description(self, temp_project: Path, monkeypatch):
        """Test that short description is included when present."""
        from unittest.mock import patch

        ldf_dir = temp_project / ".ldf"
        config = {"question_packs": ["test-pack"]}

        # Mock get_pack_info to return pack info with short description
        with patch("ldf.docs.get_pack_info") as mock_get_info:
            mock_get_info.return_value = {
                "short": "A brief description of the pack",
                "is_core": True,
            }
            result = _generate_packs_section(config, ldf_dir)

        assert "brief description" in result

    def test_handles_non_dict_questions(self, temp_project: Path):
        """Test handling questions that are plain strings instead of dicts."""
        config = {"question_packs": ["string-pack"]}
        ldf_dir = temp_project / ".ldf"

        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "string-pack.yaml"
        pack_file.write_text("""name: string-pack
questions:
  general:
    - "What is the purpose?"
    - "How does it work?"
""")

        result = _generate_packs_section(config, ldf_dir)

        assert "What is the purpose?" in result
        assert "How does it work?" in result

    def test_truncates_when_more_than_five_questions(self, temp_project: Path):
        """Test that questions are truncated when more than 5 exist."""
        config = {"question_packs": ["many-pack"]}
        ldf_dir = temp_project / ".ldf"

        packs_dir = ldf_dir / "question-packs"
        packs_dir.mkdir(exist_ok=True)
        pack_file = packs_dir / "many-pack.yaml"
        pack_file.write_text("""name: many-pack
questions:
  general:
    - question: "Question 1"
    - question: "Question 2"
    - question: "Question 3"
    - question: "Question 4"
    - question: "Question 5"
    - question: "Question 6"
    - question: "Question 7"
    - question: "Question 8"
""")

        result = _generate_packs_section(config, ldf_dir)

        assert "Questions (8)" in result
        assert "... and 3 more questions" in result


class TestGenerateMcpSection:
    """Tests for _generate_mcp_section function."""

    def test_generates_mcp_list(self):
        """Test generating MCP servers documentation."""
        config = {"mcp_servers": ["spec_inspector", "coverage_reporter"]}

        result = _generate_mcp_section(config)

        assert "## MCP Servers" in result
        assert "**2** MCP servers" in result

    def test_handles_empty_mcp_list(self):
        """Test handling when no MCP servers are configured."""
        config = {"mcp_servers": []}

        result = _generate_mcp_section(config)

        assert "**0** MCP servers" in result

    def test_shows_available_servers(self):
        """Test showing available but not enabled servers."""
        config = {"mcp_servers": []}

        result = _generate_mcp_section(config)

        assert "Available (Not Enabled)" in result

    def test_includes_server_details(self):
        """Test including server details."""
        config = {"mcp_servers": ["spec_inspector"]}

        result = _generate_mcp_section(config)

        assert "spec_inspector" in result


class TestGenerateFooter:
    """Tests for _generate_footer function."""

    def test_generates_footer(self):
        """Test generating documentation footer."""
        result = _generate_footer()

        assert "Generated by LDF" in result
        assert "github.com/LLMdotInfo/ldf" in result
        assert "---" in result
