"""TODO tool — model-driven task list management.

The model uses this tool to create, update, and read a task list.
State lives in memory for the duration of the agent loop.
"""

from pydantic import BaseModel


class TodoItem(BaseModel):
    id: int
    task: str
    status: str = "pending"  # pending | in_progress | done


class TodoState:
    """In-memory task list. One instance per agent loop run."""

    def __init__(self):
        self._items: list[TodoItem] = []
        self._next_id: int = 1

    def handle(self, action: str, **kwargs) -> str:
        """Dispatch a todo action. Returns state summary as string."""
        if action == "add":
            return self._add(kwargs.get("task", ""))
        elif action == "update":
            return self._update(kwargs.get("id", 0), kwargs.get("status", ""))
        elif action == "list":
            return self._list()
        else:
            return f"Unknown todo action: {action}. Use: add, update, list."

    def _add(self, task: str) -> str:
        if not task:
            return "Error: task text required."
        item = TodoItem(id=self._next_id, task=task)
        self._items.append(item)
        self._next_id += 1
        return self._list()

    def _update(self, item_id: int, status: str) -> str:
        if status not in ("pending", "in_progress", "done"):
            return f"Error: invalid status '{status}'. Use: pending, in_progress, done."
        for item in self._items:
            if item.id == item_id:
                item.status = status
                return self._list()
        return f"Error: no task with id {item_id}."

    def _list(self) -> str:
        if not self._items:
            return "No tasks."
        lines = []
        for item in self._items:
            marker = {"pending": "[ ]", "in_progress": "[~]", "done": "[x]"}[item.status]
            lines.append(f"{marker} {item.id}. {item.task}")
        return "\n".join(lines)


# Tool definition for the LLM API
TODO_TOOL_DEFINITION = {
    "name": "todo",
    "description": "Manage a task list. Use to plan work, track progress, or break down complex tasks.",
    "input_schema": {
        "type": "object",
        "properties": {
            "action": {
                "type": "string",
                "enum": ["add", "update", "list"],
                "description": "Action to perform: add a task, update a task's status, or list all tasks.",
            },
            "task": {
                "type": "string",
                "description": "Task description (required for 'add' action).",
            },
            "id": {
                "type": "integer",
                "description": "Task ID (required for 'update' action).",
            },
            "status": {
                "type": "string",
                "enum": ["pending", "in_progress", "done"],
                "description": "New status (required for 'update' action).",
            },
        },
        "required": ["action"],
    },
}
