# Buggy code
async def async_setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Set up the Alexa sensor platform."""
    devices: List[AlexaMediaSensor] = []
    SENSOR_TYPES = {
        "Alarm": AlarmSensor,
        "Timer": TimerSensor,
        "Reminder": ReminderSensor,
    }
    account = config[CONF_EMAIL]
    include_filter = config.get(CONF_INCLUDE_DEVICES, [])
    exclude_filter = config.get(CONF_EXCLUDE_DEVICES, [])
    account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][account]
    _LOGGER.debug("%s: Loading sensors", hide_email(account))
    if "sensor" not in account_dict["entities"]:
        (hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"]["sensor"]) = {}
    for key, device in account_dict["devices"]["media_player"].items():
        if key not in account_dict["entities"]["media_player"]:
            _LOGGER.debug(
                "%s: Media player %s not loaded yet; delaying load",
                hide_email(account),
                hide_serial(key),
            )
            if devices:
                await add_devices(
                    hide_email(account),
                    devices,
                    add_devices_callback,
                    include_filter,
                    exclude_filter,
                )
            return False
        if key not in (account_dict["entities"]["sensor"]):
            (account_dict["entities"]["sensor"][key]) = {}
            for n_type, class_ in SENSOR_TYPES.items():
                n_type_dict = (
                    account_dict["notifications"][key][n_type]
                    if key in account_dict["notifications"]
                    and n_type in account_dict["notifications"][key]
                    else {}
                )
                if (
                    n_type in ("Alarm, Timer")
                    and "TIMERS_AND_ALARMS" in device["capabilities"]
                ):
                    alexa_client = class_(
                        account_dict["entities"]["media_player"][key],
                        n_type_dict,
                        account,
                    )
                elif n_type in ("Reminder") and "REMINDERS" in device["capabilities"]:
                    alexa_client = class_(
                        account_dict["entities"]["media_player"][key],
                        n_type_dict,
                        account,
                    )
                else:
                    continue
                _LOGGER.debug(
                    "%s: Found %s %s sensor (%s) with next: %s",
                    hide_email(account),
                    hide_serial(key),
                    n_type,
                    len(n_type_dict.keys()),
                    alexa_client.state,
                )
                devices.append(alexa_client)
                (account_dict["entities"]["sensor"][key][n_type]) = alexa_client
        else:
            for alexa_client in account_dict["entities"]["sensor"][key].values():
                _LOGGER.debug(
                    "%s: Skipping already added device: %s",
                    hide_email(account),
                    alexa_client,
                )
    return await add_devices(
        hide_email(account),
        devices,
        add_devices_callback,
        include_filter,
        exclude_filter,
    )


# Traceback (TypeError)
2020-03-26 22:05:03 DEBUG (MainThread) [custom_components.alexa_media.sensor] value ('xxxxx', {'alarmTime': 1585325040000, 'automationId': None, 'createdDate': 1519416302707, 'deferredAtTime': None, 'deliveryType': None, 'deviceName': None, 'deviceSerialNumber': 'xxxxxx', 'deviceType': 'xxxxx', 'extensibleAttribute': None, 'geoLocationTriggerData': None, 'id': 'xxxxxx_REMINDER', 'lastOccurrenceTimeInMilli': 0, 'lastUpdatedDate': 0, 'musicAlarmId': None, 'musicEntity': None, 'notificationIndex': 'xxxxx-07d5-469c-b04c-bc54b39aafcf', 'originalDate': '2020-03-27', 'originalTime': '09:04:00.000', 'personProfile': None, 'provider': None, 'rRuleData': {'byMonthDays': None, 'byWeekDays': None, 'flexibleRecurringPatternType': 'ONCE_A_DAY', 'frequency': None, 'intervals': [1], 'nextTriggerTimes': None, 'notificationTimes': ['09:04:00.000'], 'recurEndDate': None, 'recurEndTime': None, 'recurStartDate': None, 'recurStartTime': None, 'recurrenceRules': ['FREQ=DAILY;BYHOUR=9;BYMINUTE=4;BYSECOND=0;INTERVAL=1;']}, 'recurrenceEligibility': False, 'recurringPattern': 'P1D', 'remainingTime': 0, 'reminderAppLabel': None, 'reminderLabel': 'Take your vitamins', 'reminderSubLabel': None, 'skillInfo': None, 'snoozedToTime': None, 'sound': {'displayName': 'Simple Alarm', 'folder': None, 'id': 'system_alerts_melodic_01', 'providerId': 'ECHO', 'sampleUrl': 'https://s3.amazonaws.com/deeappservice.prod.notificationtones/system_alerts_melodic_01.mp3'}, 'status': 'ON', 'targetPersonProfiles': None, 'timeZoneId': None, 'timerLabel': None, 'tmwNotificationProperties': None, 'triggerTime': 0, 'type': 'Reminder', 'version': '3189', 'date_time': '2020-03-27 09:04:00.000'})
2020-03-26 22:05:03 ERROR (MainThread) [homeassistant.components.sensor] Error while setting up alexa_media platform for sensor
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 179, in _async_setup_platform
await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)
File "/usr/local/lib/python3.7/asyncio/tasks.py", line 442, in wait_for
return fut.result()
File "/config/custom_components/alexa_media/sensor.py", line 151, in async_setup_entry
hass, config_entry.data, async_add_devices, discovery_info=None
File "/config/custom_components/alexa_media/helpers.py", line 111, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/sensor.py", line 118, in async_setup_platform
account,
File "/config/custom_components/alexa_media/sensor.py", line 467, in __init__
client, n_json, "alarmTime", account, f"next {self._type}", "mdi:reminder"
File "/config/custom_components/alexa_media/sensor.py", line 192, in __init__
self._process_raw_notifications()
File "/config/custom_components/alexa_media/sensor.py", line 200, in _process_raw_notifications
self._all = list(map(self._update_recurring_alarm, self._all))
File "/config/custom_components/alexa_media/sensor.py", line 253, in _update_recurring_alarm
and alarm < dt.now()
TypeError: '<' not supported between instances of 'int' and 'datetime.datetime'

# Fixed code
async def async_setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Set up the Alexa sensor platform."""
    devices: List[AlexaMediaNotificationSensor] = []
    SENSOR_TYPES = {
        "Alarm": AlarmSensor,
        "Timer": TimerSensor,
        "Reminder": ReminderSensor,
    }
    account = config[CONF_EMAIL]
    include_filter = config.get(CONF_INCLUDE_DEVICES, [])
    exclude_filter = config.get(CONF_EXCLUDE_DEVICES, [])
    account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][account]
    _LOGGER.debug("%s: Loading sensors", hide_email(account))
    if "sensor" not in account_dict["entities"]:
        (hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"]["sensor"]) = {}
    for key, device in account_dict["devices"]["media_player"].items():
        if key not in account_dict["entities"]["media_player"]:
            _LOGGER.debug(
                "%s: Media player %s not loaded yet; delaying load",
                hide_email(account),
                hide_serial(key),
            )
            if devices:
                await add_devices(
                    hide_email(account),
                    devices,
                    add_devices_callback,
                    include_filter,
                    exclude_filter,
                )
            return False
        if key not in (account_dict["entities"]["sensor"]):
            (account_dict["entities"]["sensor"][key]) = {}
            for n_type, class_ in SENSOR_TYPES.items():
                n_type_dict = (
                    account_dict["notifications"][key][n_type]
                    if key in account_dict["notifications"]
                    and n_type in account_dict["notifications"][key]
                    else {}
                )
                if (
                    n_type in ("Alarm, Timer")
                    and "TIMERS_AND_ALARMS" in device["capabilities"]
                ):
                    alexa_client = class_(
                        account_dict["entities"]["media_player"][key],
                        n_type_dict,
                        account,
                    )
                elif n_type in ("Reminder") and "REMINDERS" in device["capabilities"]:
                    alexa_client = class_(
                        account_dict["entities"]["media_player"][key],
                        n_type_dict,
                        account,
                    )
                else:
                    continue
                _LOGGER.debug(
                    "%s: Found %s %s sensor (%s) with next: %s",
                    hide_email(account),
                    hide_serial(key),
                    n_type,
                    len(n_type_dict.keys()),
                    alexa_client.state,
                )
                devices.append(alexa_client)
                (account_dict["entities"]["sensor"][key][n_type]) = alexa_client
        else:
            for alexa_client in account_dict["entities"]["sensor"][key].values():
                _LOGGER.debug(
                    "%s: Skipping already added device: %s",
                    hide_email(account),
                    alexa_client,
                )
    return await add_devices(
        hide_email(account),
        devices,
        add_devices_callback,
        include_filter,
        exclude_filter,
    )