from datetime import UTC, datetime

import django_rq
from django_rq import job
from rq import Retry

from sources.models import Source

# Default retry configuration: 3 retries with exponential backoff (2s, 4s, 8s)
DEFAULT_RETRY = Retry(max=3, interval=[2, 4, 8])


def enqueue_with_retry(func, *args, queue_name="default", **kwargs):
    """Enqueue a task with default retry configuration.

    Use this for tasks that may fail transiently and should be retried.
    Requires workers to run with --with-scheduler flag.
    """
    queue = django_rq.get_queue(queue_name)
    return queue.enqueue(func, *args, retry=DEFAULT_RETRY, **kwargs)


@job("default")
def scheduler_tick():
    """Simple heartbeat task used by the external scheduler endpoint."""
    now = datetime.now(UTC)
    return {"status": "ok", "timestamp": now.isoformat()}


@job("default")
def sync_sources():
    """Placeholder sync to demonstrate meaningful scheduler work."""
    total = Source.objects.count()
    kinds = list(Source.objects.values_list("kind", flat=True).order_by().distinct())
    return {"synced": total, "kinds": kinds}


@job("default")
def run_maintenance():
    """Run heartbeat, source sync, and GitHub sync as a batch.

    Uses django_rq.enqueue to queue the subtasks instead of .delay() chaining.
    """
    from integrations.tasks import sync_all_github_repositories

    queue = django_rq.get_queue("default")
    tick_job = queue.enqueue(scheduler_tick)
    sync_job = queue.enqueue(sync_sources)
    github_sync_job = queue.enqueue(sync_all_github_repositories)
    return {
        "tick_job_id": str(tick_job.id),
        "sync_job_id": str(sync_job.id),
        "github_sync_job_id": str(github_sync_job.id),
    }
