from django.db.models import Case, IntegerField, Q, Value, When
from django.utils import timezone


def local_today():
    return timezone.localdate()


def open_jobs_q(related=''):
    """Q filter for jobs accepting applications / shown as open."""
    prefix = f'{related}__' if related else ''
    today = local_today()
    return Q(**{f'{prefix}is_active': True}) & (
        Q(**{f'{prefix}deadline__isnull': True}) | Q(**{f'{prefix}deadline__gte': today})
    )


def closed_jobs_q(related=''):
    """Q filter for closed jobs (manual close or past deadline)."""
    prefix = f'{related}__' if related else ''
    today = local_today()
    return Q(**{f'{prefix}is_active': False}) | Q(**{f'{prefix}deadline__lt': today})


def job_is_ongoing(deadline):
    """Open-ended listing with no application deadline."""
    return deadline is None


def job_is_expired(deadline):
    return bool(deadline and deadline < local_today())


def job_is_manually_closed(*, is_active, deadline):
    """Closed by the posting company (not by an expired deadline)."""
    return not is_active


def job_is_closed(*, is_active, deadline):
    return not is_active or job_is_expired(deadline)


def job_accepts_applications(*, is_active, deadline):
    return is_active and not job_is_expired(deadline)


def job_needs_deadline_to_reactivate(*, is_active, deadline):
    """Expired listings need a new date; ongoing/manual closes can reopen as-is."""
    return job_is_expired(deadline)


def annotate_open_first(queryset):
    today = local_today()
    return queryset.annotate(
        _open_sort=Case(
            When(
                Q(is_active=True) & (Q(deadline__isnull=True) | Q(deadline__gte=today)),
                then=Value(0),
            ),
            default=Value(1),
            output_field=IntegerField(),
        )
    )
