"""
Celery Application - جدولة المهام التلقائية
"""
from celery import Celery
from celery.schedules import crontab
import os

# إعدادات Celery
CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0")
CELERY_RESULT_BACKEND = os.getenv("CELERY_RESULT_BACKEND", "redis://localhost:6379/0")

celery_app = Celery(
    "smartlife",
    broker=CELERY_BROKER_URL,
    backend=CELERY_RESULT_BACKEND,
    include=["app.tasks.device_tasks", "app.tasks.alert_tasks", "app.tasks.report_tasks"]
)

# إعدادات Celery
celery_app.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="Asia/Riyadh",
    enable_utc=True,
    task_track_started=True,
    task_time_limit=300,  # 5 دقائق
    worker_prefetch_multiplier=1,
    task_acks_late=True,
)

# جدولة المهام الدورية
celery_app.conf.beat_schedule = {
    # مزامنة الأجهزة كل 5 دقائق
    "sync-devices-every-5-minutes": {
        "task": "app.tasks.device_tasks.sync_all_devices",
        "schedule": crontab(minute="*/5"),
    },
    # فحص التنبيهات كل دقيقة
    "check-alerts-every-minute": {
        "task": "app.tasks.alert_tasks.check_device_alerts",
        "schedule": crontab(minute="*"),
    },
    # إرسال تقرير يومي
    "daily-report": {
        "task": "app.tasks.report_tasks.send_daily_report",
        "schedule": crontab(hour=8, minute=0),
    },
    # تنظيف السجلات القديمة أسبوعياً
    "cleanup-old-logs-weekly": {
        "task": "app.tasks.alert_tasks.cleanup_old_alerts",
        "schedule": crontab(day_of_week=0, hour=3, minute=0),
    },
}
