"""
Todo Manager

Classic task tracking tool for agent progress visibility.
Inspired by Claude Code's TodoWrite tool.

Features:
- Hierarchical task tracking
- Status management (pending/in_progress/done/blocked)
- Ordering and prioritization
- Rich console display
"""

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

from rich.console import Console
from rich.table import Table

console = Console()


class TodoStatus(Enum):
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    DONE = "done"
    BLOCKED = "blocked"


STATUS_ICONS = {
    TodoStatus.PENDING: "⬜",
    TodoStatus.IN_PROGRESS: "🔄",
    TodoStatus.DONE: "✅",
    TodoStatus.BLOCKED: "🚫",
}

STATUS_COLORS = {
    TodoStatus.PENDING: "dim",
    TodoStatus.IN_PROGRESS: "yellow",
    TodoStatus.DONE: "green",
    TodoStatus.BLOCKED: "red",
}


@dataclass
class TodoItem:
    """A single todo item."""
    id: str
    title: str
    status: TodoStatus = TodoStatus.PENDING
    priority: int = 0  # Higher = more important
    parent_id: Optional[str] = None
    
    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "title": self.title,
            "status": self.status.value,
            "priority": self.priority,
        }


class TodoManager:
    """
    Manages a list of todos for the current task.
    
    The agent uses this to:
    1. Break tasks into subtasks
    2. Track progress through complex work
    3. Show the user what's been done and what's left
    """
    
    def __init__(self):
        self.todos: dict[str, TodoItem] = {}
        self._counter = 0
    
    def add(self, title: str, priority: int = 0, parent_id: Optional[str] = None) -> str:
        """Add a new todo item. Returns the item ID."""
        self._counter += 1
        item_id = f"todo_{self._counter}"
        self.todos[item_id] = TodoItem(
            id=item_id,
            title=title,
            priority=priority,
            parent_id=parent_id,
        )
        return item_id
    
    def update_status(self, item_id: str, status: str) -> bool:
        """Update the status of a todo item."""
        if item_id not in self.todos:
            return False
        
        try:
            self.todos[item_id].status = TodoStatus(status)
            return True
        except ValueError:
            return False
    
    def remove(self, item_id: str) -> bool:
        """Remove a todo item."""
        if item_id in self.todos:
            del self.todos[item_id]
            return True
        return False
    
    def get_all(self) -> list[TodoItem]:
        """Get all todos, sorted by priority then creation order."""
        return sorted(
            self.todos.values(),
            key=lambda t: (-t.priority, int(t.id.split("_")[1])),
        )
    
    def get_summary(self) -> str:
        """Get a text summary of all todos."""
        if not self.todos:
            return "(no tasks tracked)"
        
        lines = []
        for item in self.get_all():
            icon = STATUS_ICONS[item.status]
            indent = "  " if item.parent_id else ""
            lines.append(f"{indent}{icon} [{item.id}] {item.title}")
        
        total = len(self.todos)
        done = sum(1 for t in self.todos.values() if t.status == TodoStatus.DONE)
        lines.append(f"\nProgress: {done}/{total} ({100*done//total if total else 0}%)")
        
        return "\n".join(lines)
    
    def display(self) -> None:
        """Pretty-print todos to console."""
        if not self.todos:
            console.print("[dim]No tracked tasks[/dim]")
            return
        
        table = Table(title="📋 Task Progress", show_lines=True)
        table.add_column("ID", style="dim", width=8)
        table.add_column("Status", width=4, justify="center")
        table.add_column("Task")
        
        for item in self.get_all():
            icon = STATUS_ICONS[item.status]
            color = STATUS_COLORS[item.status]
            title = f"  {item.title}" if item.parent_id else item.title
            table.add_row(item.id, icon, f"[{color}]{title}[/{color}]")
        
        console.print(table)
        
        total = len(self.todos)
        done = sum(1 for t in self.todos.values() if t.status == TodoStatus.DONE)
        console.print(f"[bold]Progress: {done}/{total}[/bold]")
    
    def to_dict(self) -> list[dict]:
        """Serialize all todos."""
        return [item.to_dict() for item in self.get_all()]
    
    def from_dict(self, items: list[dict]) -> None:
        """Load todos from serialized data."""
        self.todos.clear()
        for item_data in items:
            self.todos[item_data["id"]] = TodoItem(
                id=item_data["id"],
                title=item_data["title"],
                status=TodoStatus(item_data.get("status", "pending")),
                priority=item_data.get("priority", 0),
            )
