"""Exercise generator tool - Create coding exercises."""

from __future__ import annotations

from typing import Any

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


class ExerciseGeneratorTool(Tool):
    """Generate programming exercises for students."""

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

    @property
    def description(self) -> str:
        return """Create a programming exercise for students to practice.

Generates:
- Problem description with context
- Requirements and constraints
- Starter code (optional)
- Test cases to verify solution
- Hints at different levels"""

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "topic": {
                    "type": "string",
                    "description": "Programming topic (e.g., 'loops', 'functions', 'lists')",
                },
                "difficulty": {
                    "type": "string",
                    "enum": ["beginner", "intermediate", "advanced"],
                    "description": "Difficulty level",
                    "default": "beginner",
                },
                "title": {
                    "type": "string",
                    "description": "Exercise title",
                },
                "description": {
                    "type": "string",
                    "description": "Detailed problem description",
                },
                "include_starter_code": {
                    "type": "boolean",
                    "description": "Include starter code template",
                    "default": True,
                },
                "include_tests": {
                    "type": "boolean",
                    "description": "Include test cases",
                    "default": True,
                },
                "include_hints": {
                    "type": "boolean",
                    "description": "Include hints",
                    "default": True,
                },
            },
            "required": ["topic", "title", "description"],
        }

    def execute(
        self,
        topic: str,
        title: str,
        description: str,
        difficulty: str = "beginner",
        include_starter_code: bool = True,
        include_tests: bool = True,
        include_hints: bool = True,
    ) -> ToolResult:
        """Generate a formatted exercise."""
        try:
            exercise = []

            # Header
            difficulty_emoji = {
                "beginner": "🟢",
                "intermediate": "🟡",
                "advanced": "🔴",
            }
            emoji = difficulty_emoji.get(difficulty, "⚪")

            exercise.append(f"# {emoji} Exercise: {title}")
            exercise.append(f"**Topic:** {topic}")
            exercise.append(f"**Difficulty:** {difficulty.capitalize()}")
            exercise.append("")

            # Problem Description
            exercise.append("## Problem Description")
            exercise.append(description)
            exercise.append("")

            # Requirements
            exercise.append("## Requirements")
            exercise.append("Your solution should:")
            exercise.append("- Implement the functionality described above")
            exercise.append("- Handle edge cases appropriately")
            exercise.append("- Follow Python best practices")
            exercise.append("")

            # Starter Code
            if include_starter_code:
                exercise.append("## Starter Code")
                exercise.append("```python")
                exercise.append(self._generate_starter_code(topic, title))
                exercise.append("```")
                exercise.append("")

            # Test Cases
            if include_tests:
                exercise.append("## Test Your Solution")
                exercise.append("Your solution should pass these tests:")
                exercise.append("```python")
                exercise.append(self._generate_test_template(topic))
                exercise.append("```")
                exercise.append("")

            # Hints
            if include_hints:
                exercise.append("## Hints")
                exercise.append("<details>")
                exercise.append("<summary>Hint 1 (Click to reveal)</summary>")
                exercise.append("")
                exercise.append(f"Think about how {topic} works step by step.")
                exercise.append("</details>")
                exercise.append("")
                exercise.append("<details>")
                exercise.append("<summary>Hint 2 (Click to reveal)</summary>")
                exercise.append("")
                exercise.append("Break down the problem into smaller parts.")
                exercise.append("</details>")
                exercise.append("")

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

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

    def _generate_starter_code(self, topic: str, title: str) -> str:
        """Generate starter code template."""
        func_name = title.lower().replace(" ", "_").replace("-", "_")
        # Clean up function name
        func_name = "".join(c for c in func_name if c.isalnum() or c == "_")

        return f'''def {func_name}():
    """
    TODO: Implement this function

    Args:
        # Add your parameters here

    Returns:
        # Describe what the function returns
    """
    # Your code here
    pass


# Test your solution
if __name__ == "__main__":
    # Add test calls here
    result = {func_name}()
    print(result)'''

    def _generate_test_template(self, topic: str) -> str:
        """Generate test template."""
        return '''# Test cases
def test_solution():
    # Test case 1: Basic case
    # assert your_function(input) == expected_output

    # Test case 2: Edge case
    # assert your_function(edge_input) == edge_expected

    # Test case 3: Another case
    # assert your_function(another_input) == another_expected

    print("All tests passed!")

test_solution()'''
