from dataclasses import replace from typing import List, Sequence from .todo_item import Todo from .todo_list_update_todo import index_of_todo def move_todo(todos: Sequence[Todo], id: str, to_index: int) -> List[Todo]: """Move a todo to to_index in manual order (order, then array position) and renumber 0..n-1.""" source = index_of_todo(todos, id) last = len(todos) - 1 if isinstance(to_index, bool) or not isinstance(to_index, int) or to_index < 0 or to_index > last: raise ValueError(f"toIndex must be between 0 and {last}, received {to_index}") positions = sorted(range(len(todos)), key=lambda i: (todos[i].order, i)) rest = [i for i in positions if i != source] rest.insert(to_index, source) return [replace(todos[i], order=n) for n, i in enumerate(rest)]