###############################################################################
# PACKAGE: Bedtime Mode Delayed Shutdown
###############################################################################
#
# VERSION:
#   1.4 - 2026-05-21
#     - Added delayed lounge NSPanel touchscreen brightness reduction to 5.
#
#   1.3 - 2026-05-07
#     - Added downstairs lights all off script.
#     - Added main hallway nightlights 60 minute bedtime timer.
#     - Added timer cancellation if main hallway nightlights are manually turned off.
#
#   1.2 - 2026-05-04
#     - Removed script field selectors to avoid HA selector validation error.
#
#   1.1 - 2026-05-04
#     - Added lounge scene selection to "All Off".
#     - Added quiet time activation.
#
#   1.0 - 2026-05-04
#     - Initial package.
#     - Triggered by input_button.bedtime_mode or ESPHome lounge hold event.
#     - Turns listed entities off after individual delays.
#     - Only sends OFF if the entity is currently on/active.
#
# NOTES:
#   - Add more entities to bedtime_delayed_off_targets.
#   - delay_seconds is counted from the original button press.
#   - Delays are not cumulative.
#   - switch and remote entities are only turned off if state == "on".
#   - climate entities are turned off if they are not already "off".
#   - Main hallway nightlights are turned on for 60 minutes when bedtime mode runs.
#   - If the main hallway nightlights are turned off manually, the timer is cancelled.
#   - Lounge NSPanel touchscreen brightness is set to 5 after 20 seconds.
#
###############################################################################

###############################################################################
# TIMER
###############################################################################

timer:
  main_hallway_nightlights_bedtime:
    name: Main Hallway Nightlights Bedtime Timer
    duration: "01:00:00"

###############################################################################
# AUTOMATIONS
###############################################################################

automation:
  - id: bedtime_mode_delayed_shutdown
    alias: "Bedtime Mode - Delayed Shutdown"
    description: >
      Runs bedtime delayed shutdown when the bedtime button is pressed or when
      the lounge switch hold ESPHome event is seen.

    trigger:
      - platform: state
        entity_id: input_button.bedtime_mode
        id: bedtime_mode_button

      - platform: event
        event_type: esphome.lounge_switch_hold
        id: lounge_switch_hold

    variables:
      bedtime_delayed_off_targets:
        - entity_id: switch.esp_centralstairs_bottom_relay_1_main_stair_lights_lower
          delay_seconds: 0

        - entity_id: switch.esp_centralstairs_bottom_relay_2_stair_footer_lights
          delay_seconds: 0

        - entity_id: switch.esp_mainkitchenlights_relay_1_main_lights
          delay_seconds: 4

        - entity_id: switch.esp_mainkitchenlights_relay_2_benchtop_lights
          delay_seconds: 4

        - entity_id: switch.esp_entrancelightswitch_relay_1_entrance_lights
          delay_seconds: 5

        - entity_id: switch.esp_garageentrylights_relay_3_garage_lights
          delay_seconds: 10

        - entity_id: switch.esp_garageentrylights_relay_1_corridor_lights
          delay_seconds: 10

        - entity_id: switch.rinnai_neo_gas_heater_heater_operation
          delay_seconds: 1

        - entity_id: climate.lounge
          delay_seconds: 1

        - entity_id: switch.lounge_cupboard_dual_usb_xus09_l2
          delay_seconds: 2

        - entity_id: switch.tv_surround_amp_power_in_loft_x27pp
          delay_seconds: 1

        - entity_id: remote.lounge_tv
          delay_seconds: 0

    action:
      # Turn hallway nightlights on immediately before any other bedtime actions.
      - service: switch.turn_on
        target:
          entity_id: switch.main_hallway_nightlights_1_relay_1_main_hallway_nightlights

      # Start or restart the 60 minute bedtime nightlight timer.
      - service: timer.start
        target:
          entity_id: timer.main_hallway_nightlights_bedtime
        data:
          duration: "01:00:00"

      - service: script.downstairs_lights_all_off

      - service: script.lounge_set_scene
        data:
          scene_name: "All Off"

      - service: input_boolean.turn_on
        target:
          entity_id: input_boolean.quiet_time

      # Reduce the lounge NSPanel screen brightness after 20 seconds.
      - service: script.turn_on
        target:
          entity_id: script.bedtime_mode_set_lounge_nspanel_brightness_after_delay

      - repeat:
          for_each: "{{ bedtime_delayed_off_targets }}"
          sequence:
            - service: script.turn_on
              target:
                entity_id: script.bedtime_mode_turn_entity_off_after_delay
              data:
                variables:
                  target_entity: "{{ repeat.item.entity_id }}"
                  delay_seconds: "{{ repeat.item.delay_seconds | int(0) }}"

    mode: queued
    max: 5

  - id: bedtime_mode_cancel_main_hallway_nightlights_timer
    alias: "Bedtime Mode - Cancel Main Hallway Nightlights Timer"
    description: >
      Cancels the bedtime nightlights timer if something else turns the
      main hallway nightlights off.

    trigger:
      - platform: state
        entity_id: switch.main_hallway_nightlights_1_relay_1_main_hallway_nightlights
        to: "off"

    condition:
      - condition: state
        entity_id: timer.main_hallway_nightlights_bedtime
        state: "active"

    action:
      - service: timer.cancel
        target:
          entity_id: timer.main_hallway_nightlights_bedtime

    mode: single

  - id: bedtime_mode_main_hallway_nightlights_timer_finished
    alias: "Bedtime Mode - Main Hallway Nightlights Timer Finished"
    description: >
      Turns the main hallway nightlights off when the bedtime timer finishes.

    trigger:
      - platform: event
        event_type: timer.finished
        event_data:
          entity_id: timer.main_hallway_nightlights_bedtime

    condition:
      - condition: state
        entity_id: switch.main_hallway_nightlights_1_relay_1_main_hallway_nightlights
        state: "on"

    action:
      - service: switch.turn_off
        target:
          entity_id: switch.main_hallway_nightlights_1_relay_1_main_hallway_nightlights

    mode: single

###############################################################################
# SCRIPTS
###############################################################################

script:
  bedtime_mode_turn_entity_off_after_delay:
    alias: "Bedtime Mode - Turn Entity Off After Delay"
    description: >
      Waits for the supplied delay, checks whether the supplied entity is still
      on/active, then sends the correct turn_off command for its domain.

    sequence:
      - delay:
          seconds: "{{ delay_seconds | int(0) }}"

      - variables:
          target_domain: "{{ target_entity.split('.')[0] }}"

      - condition: template
        value_template: >
          {% if target_domain == 'climate' %}
            {{ states(target_entity) not in ['off', 'unknown', 'unavailable'] }}
          {% else %}
            {{ is_state(target_entity, 'on') }}
          {% endif %}

      - choose:
          - conditions:
              - condition: template
                value_template: "{{ target_domain == 'switch' }}"
            sequence:
              - service: switch.turn_off
                data:
                  entity_id: "{{ target_entity }}"

          - conditions:
              - condition: template
                value_template: "{{ target_domain == 'climate' }}"
            sequence:
              - service: climate.turn_off
                data:
                  entity_id: "{{ target_entity }}"

          - conditions:
              - condition: template
                value_template: "{{ target_domain == 'remote' }}"
            sequence:
              - service: remote.turn_off
                data:
                  entity_id: "{{ target_entity }}"

        default:
          - service: homeassistant.turn_off
            data:
              entity_id: "{{ target_entity }}"

    mode: parallel
    max: 50

  bedtime_mode_set_lounge_nspanel_brightness_after_delay:
    alias: "Bedtime Mode - Set Lounge NSPanel Brightness After Delay"
    description: >
      Waits 20 seconds after bedtime mode starts, then sets the lounge NSPanel
      touchscreen display brightness to 5.

    sequence:
      - delay:
          seconds: 20

      - service: number.set_value
        target:
          entity_id: number.lounge_nspanel_touchscreen_display_brightness
        data:
          value: 1

    mode: restart
