"""Prompt 模板服务测试."""

from pathlib import Path

import pytest

from src.ai.errors import AIError, ErrorCode
from src.ai.prompt_service import PromptTemplateService


class TestPromptTemplateService:
    """PromptTemplateService 测试."""

    def test_load_default_templates(self) -> None:
        """加载默认 prompts 目录的 5 个模板."""
        svc = PromptTemplateService()
        svc.load()
        templates = svc.list_templates()
        names = {t["name"] for t in templates}
        assert "chat_system" in names
        assert "generate_question" in names
        assert "optimize_expression" in names
        assert len(templates) == 5

    def test_render_chat_system(self) -> None:
        """渲染 chat_system 模板."""
        svc = PromptTemplateService()
        svc.load()
        result = svc.render("chat_system", {"role": "teacher"})
        assert isinstance(result, str)
        assert len(result) > 0

    def test_render_generate_question(self) -> None:
        """渲染 generate_question 模板."""
        svc = PromptTemplateService()
        svc.load()
        result = svc.render(
            "generate_question",
            {
                "subject": "数学",
                "grade": "三年级",
                "difficulty": "easy",
                "question_type": "short_answer",
                "knowledge_points": ["加减法"],
                "knowledge_point_ids": ["kp-1"],
                "count": 1,
                "prompt": "生成分数加减法",
            },
        )
        assert "数学" in result

    def test_template_not_found_raises(self) -> None:
        """模板不存在抛 AI_PROMPT_TEMPLATE_NOT_FOUND."""
        svc = PromptTemplateService()
        svc.load()
        with pytest.raises(AIError) as exc_info:
            svc.get("nonexistent_template")
        assert exc_info.value.code == ErrorCode.AI_PROMPT_TEMPLATE_NOT_FOUND

    def test_render_nonexistent_raises(self) -> None:
        """渲染不存在的模板抛异常."""
        svc = PromptTemplateService()
        svc.load()
        with pytest.raises(AIError):
            svc.render("nonexistent", {})

    def test_load_nonexistent_dir(self) -> None:
        """目录不存在时 load 不抛异常，仅记录警告."""
        svc = PromptTemplateService(templates_dir=Path("/nonexistent/path"))
        svc.load()
        assert svc.list_templates() == []

    def test_render_with_variables(self) -> None:
        """渲染带变量的模板."""
        svc = PromptTemplateService()
        svc.load()
        result = svc.render(
            "optimize_expression",
            {"text": "这是一段文字", "context": "教学场景"},
        )
        assert "这是一段文字" in result

    def test_get_returns_template(self) -> None:
        """get() 返回 PromptTemplate 对象."""
        svc = PromptTemplateService()
        svc.load()
        tpl = svc.get("chat_system")
        assert tpl.name == "chat_system"
        assert tpl.version
