"""Celery tasks for SP5 investment.

  • refresh_all_matches_task — daily beat over verified entrepreneurs.
  • recompute_snapshot_task  — queued by signals (cheap fast-path so
    receivers can fire-and-forget instead of recomputing inline).
"""
from __future__ import annotations

import logging

from celery import shared_task

logger = logging.getLogger(__name__)


@shared_task
def refresh_all_matches_task() -> int:
    from apps.smehub.investment.services import refresh_matches_for
    from apps.smehub.onboarding.models import EntrepreneurProfile

    count = 0
    qs = EntrepreneurProfile.objects.filter(
        verification_status=EntrepreneurProfile.Status.VERIFIED,
    )
    for entrepreneur in qs.iterator():
        try:
            refresh_matches_for(entrepreneur, trigger="daily_beat")
            count += 1
        except Exception as exc:  # noqa: BLE001
            logger.warning("Match refresh failed for %s: %s", entrepreneur, exc)
    return count


@shared_task
def recompute_snapshot_task(entrepreneur_id: int) -> bool:
    from apps.smehub.investment.services import (
        compile_performance_snapshot,
        compute_readiness,
    )
    from apps.smehub.onboarding.models import EntrepreneurProfile

    entrepreneur = EntrepreneurProfile.objects.filter(pk=entrepreneur_id).first()
    if entrepreneur is None:
        return False
    compile_performance_snapshot(entrepreneur, trigger="task_recompute")
    compute_readiness(entrepreneur)
    return True
