"""Todo task command for managing global todo tasks"""

from diona.project.cli.commands.base import Command
from diona.project.agent.globals import get_global_todo_task, TaskStatus


class TodoCommand(Command):
    name = "todo"
    description = "Manage global todo tasks"
    
    def execute(self, args):
        if not args:
            return self._show_help()
        
        action = args[0]
        
        if action in ("-h", "--help"):
            return self._show_help()
        elif action == "add":
            return self._add_task(args[1:])
        elif action == "list":
            return self._list_tasks(args[1:])
        elif action == "show":
            return self._show_task(args[1:])
        elif action == "update":
            return self._update_task(args[1:])
        elif action == "delete":
            return self._delete_task(args[1:])
        elif action == "complete":
            return self._complete_task(args[1:])
        elif action == "start":
            return self._start_task(args[1:])
        elif action == "cancel":
            return self._cancel_task(args[1:])
        elif action == "stats":
            return self._show_stats()
        else:
            print(f"Unknown action: {action}")
            return self._show_help()
    
    def _show_help(self):
        help_text = """Usage: todo <action> [options]

Actions:
  add <title> [description]       Add a new task
  list [status]                   List tasks (status: pending, completed, all)
  show <id>                       Show task details
  update <id> [options]           Update task
  delete <id>                     Delete task
  complete <id>                   Mark task as completed
  start <id>                      Mark task as in progress
  cancel <id>                     Cancel a task
  stats                           Show task statistics

Options for update:
  --title <title>                 Update title
  --desc <description>           Update description
  --priority <priority>           Update priority (0-10)

Examples:
  todo add "Buy groceries" "Milk, bread, eggs"
  todo list pending
  todo complete 1
  todo update 1 --title "New title" --priority 5
  todo stats"""
        print(help_text)
        return False
    
    def _add_task(self, args):
        if not args:
            print("Usage: todo add <title> [description]")
            return False
        
        title = args[0]
        description = " ".join(args[1:]) if len(args) > 1 else ""
        
        todo = get_global_todo_task()
        task = todo.add_task(title, description)
        
        print(f"Task created: #{task.id}")
        print(f"  Title: {task.title}")
        print(f"  Status: {task.status.value}")
        
        return False
    
    def _list_tasks(self, args):
        status_filter = None
        if args and args[0] != "all":
            status_map = {
                "pending": TaskStatus.PENDING,
                "completed": TaskStatus.COMPLETED,
                "in_progress": TaskStatus.IN_PROGRESS,
                "cancelled": TaskStatus.CANCELLED,
            }
            status_filter = status_map.get(args[0])
        
        todo = get_global_todo_task()
        tasks = todo.list_tasks(status_filter)
        
        if not tasks:
            print("No tasks found.")
            return False
        
        print(f"=== Tasks ({len(tasks)}) ===")
        for task in tasks:
            status_icon = {
                TaskStatus.PENDING: "[ ]",
                TaskStatus.IN_PROGRESS: "[→]",
                TaskStatus.COMPLETED: "[✓]",
                TaskStatus.CANCELLED: "[×]",
            }
            print(f"  {status_icon.get(task.status, '[?]')} #{task.id} {task.title}")
            if task.description:
                print(f"      {task.description[:50]}")
        
        return False
    
    def _show_task(self, args):
        if not args:
            print("Usage: todo show <id>")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        todo = get_global_todo_task()
        task = todo.get_task(task_id)
        
        if not task:
            print(f"Task #{task_id} not found")
            return False
        
        print(f"=== Task #{task.id} ===")
        print(f"Title: {task.title}")
        print(f"Description: {task.description}")
        print(f"Status: {task.status.value}")
        print(f"Priority: {task.priority}")
        print(f"Created: {task.created_at}")
        print(f"Updated: {task.updated_at}")
        if task.completed_at:
            print(f"Completed: {task.completed_at}")
        
        return False
    
    def _update_task(self, args):
        if len(args) < 2:
            print("Usage: todo update <id> [options]")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        title = None
        description = None
        priority = None
        
        i = 1
        while i < len(args):
            if args[i] == "--title" and i + 1 < len(args):
                title = args[i + 1]
                i += 2
            elif args[i] == "--desc" and i + 1 < len(args):
                description = args[i + 1]
                i += 2
            elif args[i] == "--priority" and i + 1 < len(args):
                try:
                    priority = int(args[i + 1])
                except ValueError:
                    print("Invalid priority")
                    return False
                i += 2
            else:
                i += 1
        
        if not any([title, description, priority is not None]):
            print("No updates provided")
            return False
        
        todo = get_global_todo_task()
        success = todo.update_task(task_id, title, description, priority)
        
        if success:
            print(f"Task #{task_id} updated")
        else:
            print(f"Task #{task_id} not found")
        
        return False
    
    def _delete_task(self, args):
        if not args:
            print("Usage: todo delete <id>")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        todo = get_global_todo_task()
        success = todo.delete_task(task_id)
        
        if success:
            print(f"Task #{task_id} deleted")
        else:
            print(f"Task #{task_id} not found")
        
        return False
    
    def _complete_task(self, args):
        if not args:
            print("Usage: todo complete <id>")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        todo = get_global_todo_task()
        success = todo.mark_completed(task_id)
        
        if success:
            print(f"Task #{task_id} marked as completed")
        else:
            print(f"Task #{task_id} not found")
        
        return False
    
    def _start_task(self, args):
        if not args:
            print("Usage: todo start <id>")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        todo = get_global_todo_task()
        success = todo.mark_in_progress(task_id)
        
        if success:
            print(f"Task #{task_id} marked as in progress")
        else:
            print(f"Task #{task_id} not found")
        
        return False
    
    def _cancel_task(self, args):
        if not args:
            print("Usage: todo cancel <id>")
            return False
        
        try:
            task_id = int(args[0])
        except ValueError:
            print("Invalid task ID")
            return False
        
        todo = get_global_todo_task()
        success = todo.mark_cancelled(task_id)
        
        if success:
            print(f"Task #{task_id} cancelled")
        else:
            print(f"Task #{task_id} not found")
        
        return False
    
    def _show_stats(self):
        todo = get_global_todo_task()
        stats = todo.get_stats()
        
        print("=== Task Statistics ===")
        print(f"Total: {stats.get('total', 0)}")
        print(f"Pending: {stats.get('pending', 0)}")
        print(f"In Progress: {stats.get('in_progress', 0)}")
        print(f"Completed: {stats.get('completed', 0)}")
        print(f"Cancelled: {stats.get('cancelled', 0)}")
        
        return False
