import json

from django_celery_beat.models import CrontabSchedule, IntervalSchedule, PeriodicTask


def ensure_notification_schedule(*, hour="8", minute="0") -> list[PeriodicTask]:
    daily, _ = CrontabSchedule.objects.get_or_create(
        minute=str(minute),
        hour=str(hour),
        day_of_week="*",
        day_of_month="*",
        month_of_year="*",
        timezone="Europe/Lisbon",
    )
    every_five, _ = IntervalSchedule.objects.get_or_create(every=5, period=IntervalSchedule.MINUTES)
    every_fifteen, _ = IntervalSchedule.objects.get_or_create(every=15, period=IntervalSchedule.MINUTES)

    definitions = [
        (
            "Portal — ciclo diário de notificações",
            {
                "task": "notifications.daily_notification_cycle",
                "crontab": daily,
                "interval": None,
                "enabled": True,
                "kwargs": json.dumps({}),
                "description": "Prepara avisos de renovação, processa agendados e repete falhas.",
            },
        ),
        (
            "Portal — processar fila de notificações",
            {
                "task": "notifications.send_scheduled_notifications",
                "interval": every_five,
                "crontab": None,
                "enabled": True,
                "kwargs": json.dumps({}),
                "description": "Processa a fila de mensagens agendadas a cada 5 minutos.",
            },
        ),
        (
            "Portal — repetir notificações falhadas",
            {
                "task": "notifications.retry_failed_notifications",
                "interval": every_fifteen,
                "crontab": None,
                "enabled": True,
                "kwargs": json.dumps({}),
                "description": "Repete falhas elegíveis a cada 15 minutos.",
            },
        ),
    ]
    tasks = []
    for name, defaults in definitions:
        task, _ = PeriodicTask.objects.update_or_create(name=name, defaults=defaults)
        tasks.append(task)
    return tasks
