"""Todo task tool for AI agent"""

from diona.project.agent.globals import get_global_todo_task, TaskStatus
from agents import function_tool


_todo_task = get_global_todo_task()


@function_tool
async def todo_task_tool(
    action: str,
    task_id: int = None,
    title: str = None,
    description: str = None,
    priority: int = None,
    status: str = None,
    limit: int = 100
) -> str:
    """Manage global todo tasks for tracking things that need to be done.
    
    This tool allows you to:
    1. Add new todo tasks
    2. List tasks by status
    3. Update task details
    4. Change task status (start, complete, cancel)
    5. Delete tasks
    6. View task statistics
    
    Args:
        action: One of "add", "list", "show", "update", "delete", "complete", "start", "cancel", "stats"
        task_id: The task ID (required for show, update, delete, complete, start, cancel actions)
        title: Task title (required for add action)
        description: Task description (optional for add action)
        priority: Task priority 0-10 (optional for add/update actions)
        status: Filter by status (pending, completed, in_progress, cancelled) for list action
        limit: Maximum number of tasks to return (default: 100)
    
    Returns:
        Result message
    """
    if action == "add":
        if not title:
            return "Error: Title is required for add action"
        
        task = _todo_task.add_task(title, description or "", priority or 0)
        return f"Task created: #{task.id}\nTitle: {task.title}\nStatus: {task.status.value}"
    
    elif action == "list":
        status_filter = None
        if status:
            status_map = {
                "pending": TaskStatus.PENDING,
                "completed": TaskStatus.COMPLETED,
                "in_progress": TaskStatus.IN_PROGRESS,
                "cancelled": TaskStatus.CANCELLED,
            }
            status_filter = status_map.get(status.lower())
        
        tasks = _todo_task.list_tasks(status_filter, limit)
        
        if not tasks:
            return "No tasks found"
        
        status_icon = {
            TaskStatus.PENDING: "[ ]",
            TaskStatus.IN_PROGRESS: "[→]",
            TaskStatus.COMPLETED: "[✓]",
            TaskStatus.CANCELLED: "[×]",
        }
        
        result = f"Tasks ({len(tasks)}):\n"
        for task in tasks:
            icon = status_icon.get(task.status, "[?]")
            result += f"{icon} #{task.id} {task.title}\n"
        
        return result
    
    elif action == "show":
        if not task_id:
            return "Error: Task ID is required for show action"
        
        task = _todo_task.get_task(task_id)
        if not task:
            return f"Task #{task_id} not found"
        
        result = f"=== Task #{task.id} ===\n"
        result += f"Title: {task.title}\n"
        result += f"Description: {task.description}\n"
        result += f"Status: {task.status.value}\n"
        result += f"Priority: {task.priority}\n"
        result += f"Created: {task.created_at}\n"
        result += f"Updated: {task.updated_at}\n"
        if task.completed_at:
            result += f"Completed: {task.completed_at}\n"
        
        return result
    
    elif action == "update":
        if not task_id:
            return "Error: Task ID is required for update action"
        
        success = _todo_task.update_task(task_id, title, description, priority)
        if success:
            return f"Task #{task_id} updated"
        else:
            return f"Task #{task_id} not found"
    
    elif action == "delete":
        if not task_id:
            return "Error: Task ID is required for delete action"
        
        success = _todo_task.delete_task(task_id)
        if success:
            return f"Task #{task_id} deleted"
        else:
            return f"Task #{task_id} not found"
    
    elif action == "complete":
        if not task_id:
            return "Error: Task ID is required for complete action"
        
        success = _todo_task.mark_completed(task_id)
        if success:
            return f"Task #{task_id} marked as completed"
        else:
            return f"Task #{task_id} not found"
    
    elif action == "start":
        if not task_id:
            return "Error: Task ID is required for start action"
        
        success = _todo_task.mark_in_progress(task_id)
        if success:
            return f"Task #{task_id} marked as in progress"
        else:
            return f"Task #{task_id} not found"
    
    elif action == "cancel":
        if not task_id:
            return "Error: Task ID is required for cancel action"
        
        success = _todo_task.mark_cancelled(task_id)
        if success:
            return f"Task #{task_id} cancelled"
        else:
            return f"Task #{task_id} not found"
    
    elif action == "stats":
        stats = _todo_task.get_stats()
        result = "=== Task Statistics ===\n"
        result += f"Total: {stats.get('total', 0)}\n"
        result += f"Pending: {stats.get('pending', 0)}\n"
        result += f"In Progress: {stats.get('in_progress', 0)}\n"
        result += f"Completed: {stats.get('completed', 0)}\n"
        result += f"Cancelled: {stats.get('cancelled', 0)}\n"
        return result
    
    else:
        return f"Error: Invalid action: {action}"
