"""SP3 linkage Celery tasks.

Schedule via Celery beat as needed; the queue handlers stay thin and
delegate the heavy lifting to ``ai_matchmaking`` / ``services``.
"""
from __future__ import annotations

import logging

from celery import shared_task

logger = logging.getLogger(__name__)


@shared_task(name="smehub.linkage.refresh_recommendations")
def refresh_recommendations_task(entrepreneur_id: int, trigger: str = "celery") -> bool:
    """Per-entrepreneur recompute of the matchmaking snapshot."""
    from apps.smehub.linkage.ai_matchmaking import refresh_recommendations
    from apps.smehub.onboarding.models import EntrepreneurProfile

    try:
        profile = EntrepreneurProfile.objects.get(pk=entrepreneur_id)
    except EntrepreneurProfile.DoesNotExist:
        return False
    refresh_recommendations(profile, trigger=trigger)
    return True


@shared_task(name="smehub.linkage.refresh_all_recommendations")
def refresh_all_recommendations_task(trigger: str = "beat") -> int:
    """Bulk refresh — beat-scheduled (e.g. nightly)."""
    from apps.smehub.linkage.ai_matchmaking import refresh_recommendations
    from apps.smehub.onboarding.models import EntrepreneurProfile

    n = 0
    for profile in EntrepreneurProfile.objects.filter(
        verification_status=EntrepreneurProfile.Status.VERIFIED,
    ).iterator():
        try:
            refresh_recommendations(profile, trigger=trigger)
            n += 1
        except Exception as exc:  # noqa: BLE001
            logger.warning("matchmaking refresh failed for entrepreneur %s: %s", profile.pk, exc)
    return n
