"""Time-zone-aware availability calculation, independent of persistence.""" from datetime import date, datetime, timedelta, timezone from zoneinfo import ZoneInfo def available_times(day: str, schedule: dict, event: dict, bookings: list[dict], now: datetime | None = None) -> list[dict]: local_date = date.fromisoformat(day) tz = ZoneInfo(schedule.get('timezone') or 'UTC') now = now or datetime.now(timezone.utc) if not event.get('active', True): return [] length = int(event.get('length_minutes') or 30) interval = int(event.get('slot_interval') or 15) if length <= 0 or interval <= 0: raise ValueError('invalid_event_duration') before = timedelta(minutes=max(0, int(event.get('buffer_before') or 0))) after = timedelta(minutes=max(0, int(event.get('buffer_after') or 0))) occupied = [] for booking in bookings: if booking.get('status') != 'accepted': continue start = datetime.fromisoformat(str(booking['start_utc']).replace('Z', '+00:00')) end = datetime.fromisoformat(str(booking['end_utc']).replace('Z', '+00:00')) occupied.append((start, end)) slots = {} midnight = datetime.combine(local_date, datetime.min.time(), tzinfo=tz) for window in schedule.get('availability') or []: if local_date.strftime('%A') not in window.get('days', []): continue first, last = int(window['startTime']), int(window['endTime']) for minute in range(first, last - length + 1, interval): start_local = midnight + timedelta(minutes=minute) start = start_local.astimezone(timezone.utc) # Skip nonexistent wall-clock times during a daylight-saving jump. if start.astimezone(tz).replace(tzinfo=None) != start_local.replace(tzinfo=None): continue end = start + timedelta(minutes=length) if start <= now: continue if any(start - before < busy_end and end + after > busy_start for busy_start, busy_end in occupied): continue key = start.strftime('%Y-%m-%dT%H:%M:%SZ') slots[key] = {'start': key, 'end': end.strftime('%Y-%m-%dT%H:%M:%SZ'), 'local': start_local.strftime('%H:%M')} return [slots[key] for key in sorted(slots)]