from typing import Any, List
from pydantic import BaseModel, Field
from .base import BaseTool
from core.todo import TodoItem, TodoManager


class TodoWriteArgs(BaseModel):
    """Arguments for TodoWrite tool"""

    todos: List[dict] = Field(..., description="The updated todo list")


class TodoReadArgs(BaseModel):
    """Arguments for TodoRead tool - no parameters needed"""

    pass


class TodoWriteTool(BaseTool):
    """Tool for writing/updating todo list"""

    name = "todowrite"
    description = """Use this tool to create and manage a structured task list for your current coding session.

When to Use:
- Complex multi-step tasks (3+ steps)
- User provides multiple tasks
- When starting work on a task (mark as in_progress)
- After completing a task (mark as completed)

Task States:
- pending: Task not yet started (default)
- in_progress: Currently working on
- completed: Task finished successfully

Each todo only requires: content (description). Optional: status, priority, id (auto-generated if not provided).

Example:
{"todos": [{"content": "Create user model"}, {"content": "Implement login API"}, {"content": "Add tests"}]}"""
    args_schema = TodoWriteArgs

    def __init__(self, session_id: str):
        self.session_id = session_id
        self.manager = TodoManager()

    async def run(self, todos: List[dict]) -> str:
        """Execute the tool"""
        # 过滤空列表调用
        if not todos:
            return "No todos provided. Please provide at least one todo item with 'content' field."

        # Convert dict to TodoItem
        todo_items = [TodoItem(**todo) for todo in todos]

        # Update todos
        await self.manager.update(self.session_id, todo_items)

        # Return result
        active_count = self.manager.get_active_count(todo_items)
        return f"Todos updated successfully. {active_count} active todos."


class TodoReadTool(BaseTool):
    """Tool for reading todo list"""

    name = "todoread"
    description = "Use this tool to read your current todo list"
    args_schema = TodoReadArgs

    def __init__(self, session_id: str):
        self.session_id = session_id
        self.manager = TodoManager()

    async def run(self) -> str:
        """Execute the tool"""
        todos = await self.manager.get(self.session_id)

        if not todos:
            return "No todos found."

        # Format output
        active_count = self.manager.get_active_count(todos)
        result = f"{active_count} active todos:\n\n"

        for todo in todos:
            status_icon = {
                "pending": "⏳",
                "in_progress": "🔄",
                "completed": "✅",
                "cancelled": "❌",
            }.get(todo.status, "❓")

            result += f"{status_icon} [{todo.status}] {todo.content}\n"

        return result
