File size: 11,597 Bytes
5be081e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""
Service Layer for Interactive Todo Application (v2.0.0)

Owner: Service Logic Agent
Purpose: Business logic orchestration, validation, and error translation
Architecture: Async/Await with Pydantic models

Constitutional Constraints:
- ALLOWED: Business rule validation, orchestration between CLI and Repository, error handling
- FORBIDDEN: Direct database connections (uses repository.py), User input (input()),
             User output (print()), SQL queries, Rich UI output.

All service functions return dictionaries with consistent structure:
- {'success': bool, 'message': str, 'data': Any | None}
"""

import logging
import dateparser
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any
from src.models import Task, TaskCreate, TaskUpdate, TaskStatus, RecurrenceInterval, Priority
import src.repository as repository
from src.recurrence_engine import create_recurring_task_instance

logger = logging.getLogger("services")

def parse_natural_date(date_str: str) -> Optional[datetime]:
    """
    Parse natural language date string into datetime object.

    Args:
        date_str: Human-readable date string

    Returns:
        Datetime object or None if parsing fails
    """
    if not date_str or not date_str.strip():
        return None

    # dateparser configuration
    settings = {
        'RETURN_AS_TIMEZONE_AWARE': False,  # Store as local/naive for now to match project simple datetime usage
        'PREFER_DATES_FROM': 'future',
        'PREFER_DAY_OF_MONTH': 'current'
    }

    try:
        parsed_date = dateparser.parse(date_str, settings=settings)
        return parsed_date
    except Exception as e:
        logger.warning(f"Failed to parse date string '{date_str}': {e}")
        return None

async def create_task(task_data: TaskCreate) -> Dict[str, Any]:
    """
    Orchestrate task creation with validation.

    Args:
        task_data: Pydantic model containing task creation fields

    Returns:
        Dict with success status, message, and created task data
    """
    try:
        # Pydantic already handled basic type validation and length constraints via TaskCreate
        # Extract data and call repository
        new_task = await repository.create_task(
            title=task_data.title.strip(),
            description=task_data.description.strip() if task_data.description else None,
            priority=task_data.priority,
            category=task_data.category.strip() if task_data.category else None,
            due_date=task_data.due_date,
            recurrence_interval=task_data.recurrence_interval
        )

        return {
            "success": True,
            "message": f"Task '{new_task.title}' created successfully.",
            "data": new_task
        }
    except Exception as e:
        logger.error(f"Error creating task: {e}")
        return {
            "success": False,
            "message": f"Failed to create task: {str(e)}",
            "data": None
        }

async def get_tasks(
    status: Optional[TaskStatus] = None,
    category: Optional[str] = None,
    priority: Optional[Priority] = None,
    parent_task_id: Optional[int] = None,
    recurrence_interval: Optional[str] = None,
    due_before: Optional[datetime] = None,
    due_after: Optional[datetime] = None,
    sort_by: str = 'date'
) -> Dict[str, Any]:
    """
    Retrieve tasks with filtering and sorting.

    Args:
        status: Filter by completion status
        category: Filter by category name
        priority: Filter by priority level
        parent_task_id: Filter by parent task
        recurrence_interval: Filter by recurrence interval
        due_before: Filter by due date before
        due_after: Filter by due date after
        sort_by: Sorting criterion ('date', 'alpha', 'priority')

    Returns:
        Dict with success status, message, and list of tasks
    """
    try:
        # Normalize status and priority to string values for repository
        status_val = status
        if status and hasattr(status, 'value'):
            status_val = status.value
        elif status:
            status_val = str(status)

        priority_val = priority
        if priority and hasattr(priority, 'value'):
            priority_val = priority.value
        elif priority:
            priority_val = str(priority)

        tasks = await repository.get_all_tasks(
            status=status_val,
            category=category,
            priority=priority_val,
            parent_task_id=parent_task_id,
            recurrence_interval=recurrence_interval,
            due_before=due_before,
            due_after=due_after,
            sort_by=sort_by
        )

        return {
            "success": True,
            "message": f"Retrieved {len(tasks)} tasks.",
            "data": tasks
        }
    except Exception as e:
        logger.error(f"Error retrieving tasks: {e}")
        return {
            "success": False,
            "message": f"Failed to retrieve tasks: {str(e)}",
            "data": []
        }

async def update_task(task_id: int, update_data: TaskUpdate) -> Dict[str, Any]:
    """
    Update an existing task with validation.

    Args:
        task_id: ID of the task to update
        update_data: Pydantic model containing update fields

    Returns:
        Dict with success status, message, and updated task data
    """
    try:
        # Business Validation: Ensure task exists
        existing_task = await repository.get_task_by_id(task_id)
        if not existing_task:
            return {
                "success": False,
                "message": f"Task with ID {task_id} not found.",
                "data": None
            }

        # Convert Pydantic model to dict, excluding unset fields
        updates = update_data.model_dump(exclude_unset=True)
        if not updates:
            return {
                "success": True,
                "message": "No changes requested.",
                "data": existing_task
            }

        # Handle string stripping for updates
        if 'title' in updates and updates['title']:
            updates['title'] = updates['title'].strip()
        if 'description' in updates and updates['description']:
            updates['description'] = updates['description'].strip()
        if 'category' in updates and updates['category']:
            updates['category'] = updates['category'].strip()

        updated_task = await repository.update_task(task_id, **updates)

        return {
            "success": True,
            "message": f"Task {task_id} updated successfully.",
            "data": updated_task
        }
    except Exception as e:
        logger.error(f"Error updating task {task_id}: {e}")
        return {
            "success": False,
            "message": f"Failed to update task: {str(e)}",
            "data": None
        }

async def delete_task(task_id: int) -> Dict[str, Any]:
    """
    Delete a task.

    Args:
        task_id: ID of the task to delete

    Returns:
        Dict with success status and message
    """
    try:
        # Business Validation: Ensure task exists
        existing_task = await repository.get_task_by_id(task_id)
        if not existing_task:
            return {
                "success": False,
                "message": f"Task with ID {task_id} not found.",
                "data": None
            }

        success = await repository.delete_task(task_id)
        if success:
            return {
                "success": True,
                "message": f"Task {task_id} deleted successfully.",
                "data": None
            }
        else:
            return {
                "success": False,
                "message": f"Failed to delete task {task_id}.",
                "data": None
            }
    except Exception as e:
        logger.error(f"Error deleting task {task_id}: {e}")
        return {
            "success": False,
            "message": f"Error during deletion: {str(e)}",
            "data": None
        }

async def search_tasks(query: str) -> Dict[str, Any]:
    """
    Search for tasks by query string.

    Args:
        query: Search term

    Returns:
        Dict with success status, message, and matching tasks
    """
    if not query or not query.strip():
        return {
            "success": False,
            "message": "Search query cannot be empty.",
            "data": []
        }

    try:
        tasks = await repository.search_tasks(query.strip())
        return {
            "success": True,
            "message": f"Found {len(tasks)} tasks matching '{query}'.",
            "data": tasks
        }
    except Exception as e:
        logger.error(f"Error searching tasks for '{query}': {e}")
        return {
            "success": False,
            "message": f"Search failed: {str(e)}",
            "data": []
        }

async def toggle_task_completion(task_id: int) -> Dict[str, Any]:
    """
    Toggle the completion status of a task.

    Args:
        task_id: ID of the task to toggle

    Returns:
        Dict with success status, message, and updated task data
    """
    try:
        existing_task = await repository.get_task_by_id(task_id)
        if not existing_task:
            return {
                "success": False,
                "message": f"Task with ID {task_id} not found.",
                "data": None
            }

        # Determine new status
        is_completed = (existing_task.status == TaskStatus.PENDING)
        new_status = TaskStatus.COMPLETED if is_completed else TaskStatus.PENDING

        updated_task = await repository.update_task(task_id, status=new_status)

        # Trigger recurrence logic if marking as completed
        new_task_msg = ""
        if is_completed and updated_task.recurrence_interval != RecurrenceInterval.NONE:
            new_instance_id = await create_recurring_task_instance(
                completed_task_id=task_id,
                current_due_date=updated_task.due_date,
                recurrence_interval=updated_task.recurrence_interval
            )
            if new_instance_id:
                new_task_msg = f" New recurring instance created: {new_instance_id}."

        status_str = "completed" if is_completed else "pending"
        return {
            "success": True,
            "message": f"Task {task_id} marked as {status_str}.{new_task_msg}",
            "data": updated_task
        }
    except Exception as e:
        logger.error(f"Error toggling task {task_id}: {e}")
        return {
            "success": False,
            "message": f"Failed to toggle status: {str(e)}",
            "data": None
        }

async def get_task_history(root_task_id: int) -> Dict[str, Any]:
    """
    Get all instances of a recurring task series.

    Args:
        root_task_id: ID of the root task

    Returns:
        Dict with success status, message, and list of tasks
    """
    try:
        tasks = await repository.get_task_history(root_task_id)
        if not tasks:
            return {
                "success": False,
                "message": f"No history found for task {root_task_id}.",
                "data": []
            }

        return {
            "success": True,
            "message": f"Found {len(tasks)} instances in series.",
            "data": tasks
        }
    except Exception as e:
        logger.error(f"Error retrieving task history for {root_task_id}: {e}")
        return {
            "success": False,
            "message": f"Failed to retrieve history: {str(e)}",
            "data": []
        }