"""SP2 Celery tasks.

Backed by Celery beat for periodic execution. The schedule entries live in
`config.celery` (or are added through `django_celery_beat`'s admin).
"""
from __future__ import annotations

import logging

from celery import shared_task

logger = logging.getLogger(__name__)


@shared_task(name="smehub.incubation.remind_pending_judges")
def remind_pending_judges_task(days_pending: int = 3) -> int:
    """FRSME-INC021. Beat schedule should run this daily."""
    from apps.smehub.incubation.services import remind_pending_judges

    sent = remind_pending_judges(days_pending=days_pending)
    logger.info("smehub-incubation: sent %s judge reminders (>=%sd pending)", sent, days_pending)
    return sent


@shared_task(name="smehub.incubation.dispatch_eligibility_alerts")
def dispatch_eligibility_alerts_task(programme_id: int) -> int:
    """Async fan-out for FRSME-INC007 — enqueued from the publish view."""
    from apps.smehub.incubation.models import Programme
    from apps.smehub.incubation.services import notify_eligible_entrepreneurs

    try:
        programme = Programme.objects.get(pk=programme_id)
    except Programme.DoesNotExist:
        logger.warning("dispatch_eligibility_alerts: programme %s not found", programme_id)
        return 0
    return notify_eligible_entrepreneurs(programme)


@shared_task(name="smehub.incubation.enrol_cohort_in_courses")
def enrol_cohort_in_courses_task(cohort_id: int) -> dict:
    """FRSME-INC024 — async fan-out triggered on cohort confirmation.

    Failed enrolments are surfaced to administrators via FRSME-INC025
    follow-up wiring; this task records summary counts only.
    """
    from apps.smehub.incubation.models import Cohort
    from apps.smehub.incubation.services import enrol_cohort_in_courses

    try:
        cohort = Cohort.objects.select_related("programme").get(pk=cohort_id)
    except Cohort.DoesNotExist:
        logger.warning("enrol_cohort_in_courses: cohort %s not found", cohort_id)
        return {}
    summary = enrol_cohort_in_courses(cohort)
    logger.info("smehub-incubation: cohort %s REP enrol summary=%s", cohort_id, summary)
    return summary


@shared_task(name="smehub.incubation.regenerate_progress_record")
def regenerate_progress_record_task(cohort_member_id: int) -> bool:
    """Ensure a member's ProgressRecord exists.

    This used to rebuild ``course_completions`` from REP LMS enrolment data. With
    learning on Moodle, course completions arrive via a Moodle feed (future work
    through MEL), so this no longer sources completions from the retired REP
    tables — it only guarantees the ProgressRecord row is present.
    """
    from apps.smehub.incubation.models import CohortMember, ProgressRecord

    try:
        member = CohortMember.objects.select_related("cohort__programme").get(pk=cohort_member_id)
    except CohortMember.DoesNotExist:
        return False

    ProgressRecord.objects.get_or_create(cohort_member=member)
    return True
