"""Quiz generator tool - Create assessments."""

from __future__ import annotations

from typing import Any

from agenai.agent.tools.base import Tool, ToolResult


class QuizGeneratorTool(Tool):
    """Generate quizzes to test student understanding."""

    @property
    def name(self) -> str:
        return "create_quiz"

    @property
    def description(self) -> str:
        return """Create a quiz to test student understanding of programming concepts.

Generates different question types:
- Multiple choice questions
- True/False questions
- Fill in the blank (code completion)
- Short coding questions"""

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "title": {
                    "type": "string",
                    "description": "Quiz title",
                },
                "topics": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Topics to cover in the quiz",
                },
                "questions": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string",
                                "enum": ["multiple_choice", "true_false", "fill_blank", "coding"],
                            },
                            "question": {"type": "string"},
                            "options": {
                                "type": "array",
                                "items": {"type": "string"},
                            },
                            "correct_answer": {"type": "string"},
                            "explanation": {"type": "string"},
                        },
                    },
                    "description": "Quiz questions",
                },
                "difficulty": {
                    "type": "string",
                    "enum": ["beginner", "intermediate", "advanced"],
                    "default": "beginner",
                },
            },
            "required": ["title", "topics", "questions"],
        }

    def execute(
        self,
        title: str,
        topics: list[str],
        questions: list[dict],
        difficulty: str = "beginner",
    ) -> ToolResult:
        """Generate a formatted quiz."""
        try:
            quiz = []

            # Header
            quiz.append(f"# Quiz: {title}")
            quiz.append(f"**Topics:** {', '.join(topics)}")
            quiz.append(f"**Difficulty:** {difficulty.capitalize()}")
            quiz.append(f"**Questions:** {len(questions)}")
            quiz.append("")
            quiz.append("---")
            quiz.append("")

            # Questions
            for i, q in enumerate(questions, 1):
                q_type = q.get("type", "multiple_choice")
                question = q.get("question", "")
                options = q.get("options", [])
                correct = q.get("correct_answer", "")
                explanation = q.get("explanation", "")

                quiz.append(f"## Question {i}")
                quiz.append("")

                if q_type == "multiple_choice":
                    quiz.append(question)
                    quiz.append("")
                    for j, opt in enumerate(options):
                        letter = chr(65 + j)  # A, B, C, D
                        quiz.append(f"- [ ] **{letter}.** {opt}")
                    quiz.append("")

                elif q_type == "true_false":
                    quiz.append(question)
                    quiz.append("")
                    quiz.append("- [ ] True")
                    quiz.append("- [ ] False")
                    quiz.append("")

                elif q_type == "fill_blank":
                    quiz.append(question)
                    quiz.append("")
                    quiz.append("```python")
                    quiz.append("# Fill in the blank: ___________")
                    quiz.append("```")
                    quiz.append("")

                elif q_type == "coding":
                    quiz.append(question)
                    quiz.append("")
                    quiz.append("```python")
                    quiz.append("# Write your code here")
                    quiz.append("")
                    quiz.append("```")
                    quiz.append("")

                quiz.append("---")
                quiz.append("")

            # Answer Key (at the end)
            quiz.append("## Answer Key")
            quiz.append("")
            quiz.append("<details>")
            quiz.append("<summary>Click to reveal answers</summary>")
            quiz.append("")

            for i, q in enumerate(questions, 1):
                correct = q.get("correct_answer", "N/A")
                explanation = q.get("explanation", "")
                quiz.append(f"**Question {i}:** {correct}")
                if explanation:
                    quiz.append(f"  - *{explanation}*")
                quiz.append("")

            quiz.append("</details>")

            return ToolResult.ok("\n".join(quiz))

        except Exception as e:
            return ToolResult.fail(f"Error generating quiz: {e}")
