"""Todo management for tracking task progress."""

from pydantic import BaseModel, Field
from typing import Literal
import json
from pathlib import Path


class Todo(BaseModel):
    """A single todo item."""
    content: str = Field(description="Brief description of the task")
    activeForm: str = Field(description="Present continuous form shown during execution (e.g., 'Running tests')")
    status: Literal["pending", "in_progress", "completed"] = Field(
        description="Current status: pending, in_progress, completed"
    )
    id: str | None = Field(default=None, description="Unique identifier (auto-generated if not provided)")


class TodoStorage:
    """Simple file-based storage for todos."""

    def __init__(self, storage_dir: str = ".agent_storage"):
        """Initialize todo storage.

        Args:
            storage_dir: Directory to store todo files
        """
        self.storage_dir = Path(storage_dir)
        self.storage_dir.mkdir(exist_ok=True)

    def get_todo_file(self, session_id: str) -> Path:
        """Get the todo file path for a session.

        Args:
            session_id: Session ID

        Returns:
            Path to the todo file
        """
        return self.storage_dir / f"todo_{session_id}.json"

    def save(self, session_id: str, todos: list[Todo]) -> None:
        """Save todos for a session.

        Args:
            session_id: Session ID
            todos: List of todos to save
        """
        todo_file = self.get_todo_file(session_id)
        with open(todo_file, 'w', encoding='utf-8') as f:
            json.dump([todo.model_dump() for todo in todos], f, indent=2, ensure_ascii=False)

    def load(self, session_id: str) -> list[Todo]:
        """Load todos for a session.

        Args:
            session_id: Session ID

        Returns:
            List of todos, or empty list if none exist
        """
        todo_file = self.get_todo_file(session_id)
        if not todo_file.exists():
            return []

        try:
            with open(todo_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            return [Todo(**item) for item in data]
        except (json.JSONDecodeError, ValueError):
            return []


# Global storage instance
_storage = TodoStorage()


def get_storage() -> TodoStorage:
    """Get the global todo storage instance."""
    return _storage


def set_storage(storage: TodoStorage) -> None:
    """Set a custom todo storage instance."""
    global _storage
    _storage = storage
