"""ARQ reminder job for due tasks — sends notifications for overdue/due tasks."""

from __future__ import annotations

import logging
from datetime import datetime, timezone

from app.core.db import get_session_factory

logger = logging.getLogger(__name__)


async def tasks_due_reminder(ctx: dict) -> None:
    """Check for due tasks and send notifications to assigned users.

    Runs daily at 8:00 via cron. Finds all non-done tasks with due_date <= now
    and creates a notification for the assigned user.
    """
    from app.plugins.builtins.tasks.services import get_due_tasks
    from app.models.tenant import Tenant
    from app.core.notifications import create_notification
    from sqlalchemy import select

    factory = get_session_factory()
    async with factory() as db:
        result = await db.execute(select(Tenant))
        tenants = result.scalars().all()

        total_notified = 0
        for tenant in tenants:
            try:
                due_tasks = await get_due_tasks(db, tenant.id)
                for task in due_tasks:
                    if not task.get("assigned_to"):
                        continue
                    await create_notification(
                        db,
                        user_id=task["assigned_to"],
                        tenant_id=str(tenant.id),
                        type="task_due",
                        title=f"Task due: {task['title']}",
                        body=f"Task '{task['title']}' is due. Priority: {task['priority']}",
                        data={"task_id": task["id"], "due_date": task.get("due_date")},
                    )
                    total_notified += 1
            except Exception:
                logger.warning(f"Failed to process due tasks for tenant {tenant.id}", exc_info=True)

        if total_notified > 0:
            logger.info(f"Tasks reminder: sent {total_notified} notifications")
        await db.commit()
