import json

from django_celery_beat.models import CrontabSchedule, IntervalSchedule, PeriodicTask


def ensure_monitoring_schedule():
    interval, _ = IntervalSchedule.objects.get_or_create(
        every=1,
        period=IntervalSchedule.MINUTES,
    )
    monitor_task, _ = PeriodicTask.objects.update_or_create(
        name="K4W — Monitorizar websites",
        defaults={
            "task": "monitoring.run_due_monitors",
            "interval": interval,
            "crontab": None,
            "enabled": True,
            "kwargs": json.dumps({}),
            "description": "Executa os monitores de websites que chegaram à próxima data de verificação.",
        },
    )
    cleanup_schedule, _ = CrontabSchedule.objects.get_or_create(
        minute="20",
        hour="3",
        day_of_week="*",
        day_of_month="*",
        month_of_year="*",
        timezone="Europe/Lisbon",
    )
    cleanup_task, _ = PeriodicTask.objects.update_or_create(
        name="K4W — Limpar histórico antigo de monitorização",
        defaults={
            "task": "monitoring.cleanup_history",
            "crontab": cleanup_schedule,
            "interval": None,
            "enabled": True,
            "kwargs": json.dumps({}),
            "description": "Remove verificações antigas de acordo com a retenção configurada.",
        },
    )
    return [monitor_task, cleanup_task]
