"""Auto-BYE gamers whose room seat token cost lapsed past the renewal grace.

The lazy `_expire_lapsed_seats` inside the room view / gatekeeper /
gate-view already frees lapsed seats on every access; this command is the
cron backstop for rooms nobody reopens — a mid-game table left idle past
the grace window (filled_at + 2*renewal_period) would otherwise keep its
stuck seats forever. Mirrors `delete_stale_my_sea_draws`. No flags;
idempotent.

Usage:
    python manage.py expire_lapsed_room_seats
"""
from django.core.management.base import BaseCommand

from apps.epic.models import GateSlot, Room
from apps.epic.views import _expire_lapsed_seats


class Command(BaseCommand):
    help = "Free room seats whose token cost lapsed past the renewal grace."

    def handle(self, *args, **options):
        rooms = Room.objects.filter(
            gate_slots__status=GateSlot.FILLED,
            gate_slots__filled_at__isnull=False,
        ).distinct()
        freed = 0
        for room in rooms:
            before = room.gate_slots.filter(status=GateSlot.FILLED).count()
            _expire_lapsed_seats(room)
            if room.gate_slots.filter(status=GateSlot.FILLED).count() < before:
                freed += 1
        self.stdout.write(self.style.SUCCESS(
            f"Freed lapsed seats in {freed} room{'s' if freed != 1 else ''}."
        ))
