"""Schedule overview endpoint."""

from __future__ import annotations

from aiohttp import web

from dobby.models import ScheduleType, TaskStatus


async def get_schedule(request: web.Request) -> web.Response:
    """Return all scheduled/recurring tasks and todos with due dates."""
    store = request.app["store"]

    # Fetch scheduled tasks (cron, interval, after) — active ones
    scheduled_tasks = await store.get_scheduled_tasks()

    # Also include pending tasks with non-once schedules
    all_tasks = await store.list_tasks(limit=500)
    pending_scheduled = [
        t for t in all_tasks
        if t.schedule.type != ScheduleType.ONCE
        and t.status in (TaskStatus.PENDING, TaskStatus.RUNNING)
        and t.id not in {st.id for st in scheduled_tasks}
    ]
    scheduled_tasks.extend(pending_scheduled)

    # Fetch open todos with due dates
    all_todos = await store.list_todos(status="open")
    due_todos = [t for t in all_todos if t.due_date is not None]

    # Build unified items list
    items: list[dict] = []
    for task in scheduled_tasks:
        next_run = task.next_run_at
        if next_run is None and task.schedule.type in (ScheduleType.CRON, ScheduleType.INTERVAL):
            try:
                from dobby.core.queue import QueueManager
                next_run = QueueManager.compute_next_run(task)
            except Exception:
                pass

        item = {
            "kind": "task",
            "id": task.id,
            "project": task.project,
            "title": task.title or task.description,
            "status": task.status.value if hasattr(task.status, "value") else str(task.status),
            "schedule_type": task.schedule.type.value,
            "schedule_expr": task.schedule.expr or task.schedule.every,
            "next_run_at": next_run.isoformat() if next_run else None,
            "last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
            "created_at": task.created_at.isoformat(),
        }
        items.append(item)

    for todo in due_todos:
        items.append({
            "kind": "todo",
            "id": todo.id,
            "project": todo.project,
            "title": todo.description,
            "status": todo.status.value,
            "schedule_type": "due_date",
            "schedule_expr": None,
            "next_run_at": todo.due_date.isoformat() if todo.due_date else None,
            "last_run_at": None,
            "created_at": todo.created_at.isoformat(),
        })

    # Sort by next_run_at (nulls last)
    items.sort(key=lambda x: x["next_run_at"] or "9999-12-31T23:59:59")

    return web.json_response(items)
