################################################################################
# PACKAGE: Underhouse Entrance Auto Lights
################################################################################
#
# Version:
#   1.2 - 2026-05-12
#     - Added fast Zigbee2MQTT FP1-style event triggers:
#         sensor.underhouse_mmwave_sensor_x23ms_presence_event = enter
#         sensor.underhouse_mmwave_sensor_x23ms_presence_event = approach
#     - Keeps binary presence as a backup trigger and as the clear/off condition.
#     - This should behave closer to the previous Node-RED automation.
#
# Notes:
#   - The UI may show the binary sensor as "Detected", but the YAML state is
#     normally "on".
#   - The presence_event sensor can react earlier than the binary presence sensor.
#   - The event sensor is used to turn lights on quickly, but not to decide when
#     the area is clear, because it may remain on its last event value.
#
################################################################################

automation:
  - id: underhouse_entrance_auto_lights
    alias: "Underhouse Entrance - Auto Lights"
    description: "Turns underhouse entrance lights on from Zigbee2MQTT mmWave enter/approach/presence, then off 400 seconds after presence clears."
    mode: restart
    max_exceeded: silent

    trigger:
      - platform: state
        entity_id: sensor.underhouse_mmwave_sensor_x23ms_presence_event
        to: "enter"

      - platform: state
        entity_id: sensor.underhouse_mmwave_sensor_x23ms_presence_event
        to: "approach"

      - platform: state
        entity_id: binary_sensor.underhouse_mmwave_sensor_x23ms_presence
        to: "on"

    action:
      - alias: "Turn on the underhouse entrance lights"
        action: switch.turn_on
        target:
          entity_id: switch.esp_underhouselights_underhouse_entrance_lights

      - alias: "Wait until the mmWave presence sensor is clear"
        wait_template: >
          {{ is_state('binary_sensor.underhouse_mmwave_sensor_x23ms_presence', 'off') }}

      - alias: "Keep lights on for 400 seconds after presence clears"
        delay:
          seconds: 400

      - alias: "Only continue if presence is still clear"
        condition: state
        entity_id: binary_sensor.underhouse_mmwave_sensor_x23ms_presence
        state: "off"

      - alias: "Turn off the underhouse entrance lights"
        action: switch.turn_off
        target:
          entity_id: switch.esp_underhouselights_underhouse_entrance_lights
