"""Celery application factory.

Celery is optional in dev (`CELERY_TASK_ALWAYS_EAGER=True`).
In production a Redis broker can be enabled via `REDIS_URL`.
"""

from __future__ import annotations

import os

from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")

app = Celery("simorgh")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

# ---------------------------------------------------------------------------
# Celery Beat schedule
# ---------------------------------------------------------------------------
app.conf.beat_schedule = {
    # Tick every minute to dispatch due ScheduledRule rows.
    "automation.tick_scheduled_rules": {
        "task": "automation.tick_scheduled_rules",
        "schedule": 60.0,  # seconds
    },
    # Subscription lifecycle maintenance
    "subscription.check_expiring_trials": {
        "task": "subscription.check_expiring_trials",
        "schedule": 6 * 60 * 60,  # every 6 hours
    },
    "subscription.expire_subscriptions": {
        "task": "subscription.expire_subscriptions",
        "schedule": 60 * 60,  # every 1 hour
    },
    "subscription.expire_addon_features": {
        "task": "subscription.expire_addon_features",
        "schedule": 60 * 60,  # every 1 hour
    },
    # HR maintenance tasks
    "hr.accrue_monthly_leave": {
        "task": "hr.accrue_monthly_leave",
        "schedule": 30 * 24 * 60 * 60,  # ~monthly (30 days); use crontab for exact 1st of month
    },
    "hr.check_document_expiry": {
        "task": "hr.check_document_expiry",
        "schedule": 24 * 60 * 60,  # daily
    },
    "hr.sync_on_leave_status": {
        "task": "hr.sync_on_leave_status",
        "schedule": 24 * 60 * 60,  # daily
    },
    # Agent orchestration — check for stuck pipelines every 5 minutes
    "automation.check_stuck_pipelines": {
        "task": "automation.check_stuck_pipelines",
        "schedule": 5 * 60,  # every 5 minutes
    },
}
app.conf.beat_scheduler = "django_celery_beat.schedulers:DatabaseScheduler"


@app.task(bind=True)
def debug_task(self) -> None:  # pragma: no cover - debugging helper
    print(f"Request: {self.request!r}")
