from background_task import background
from django.utils import timezone
from django.db import transaction
from django.conf import settings

from .models import Tournament
from .models.enums import RegistrationStatus

@background(schedule=settings.BACKGROUND_SCHEDULED_TASK_INTERVAL * 60)  # Run every 30 minutes (30*60 seconds)
def background_task_check_confirmation_deadlines():
    #DEBUG ONLY NOT NEEDED ON PROD
    print("background_task Running confirmation deadline check...")
    check_confirmation_deadlines()

def check_confirmation_deadlines():
    """
    Periodic task to check for expired confirmation deadlines
    and notify the next team in the waiting list.
    """
    now = timezone.now()
    print(f"[{now}] Running confirmation deadline check...")

    # Get all tournaments with online registrations
    tournaments = Tournament.objects.filter(
        team_registrations__player_registrations__registration_status=RegistrationStatus.PENDING,
        team_registrations__player_registrations__registered_online=True
    ).distinct()

    total_processed = 0
    for tournament in tournaments:
        processed = tournament.check_all_confirmation_deadlines()
        total_processed += processed

    print(f"Processed confirmation deadlines for {total_processed} teams")
