alias: Lounge - Manual Override Detected
description: >
  Turns on lounge_manual_override when a human makes a meaningful change to the
  lounge light (brightness, colour temp, colour, or manual on/off).

trigger:
  - platform: state
    entity_id: light.lounge_light  # <-- CHANGE THIS to your light

condition:
  # Ignore startup / null transitions
  - condition: template
    value_template: "{{ trigger.from_state is not none and trigger.to_state is not none }}"

  # Only set override if currently OFF
  - condition: state
    entity_id: input_boolean.lounge_manual_override  # <-- CHANGE IF NEEDED
    state: "off"

  # Treat events with no parent_id as "manual-ish"
  - condition: template
    value_template: "{{ trigger.to_state.context.parent_id is none }}"

  # Meaningful change logic (MUST render ONLY true/false)
  - condition: template
    value_template: >
      {% set from_s = trigger.from_state %}
      {% set to_s   = trigger.to_state %}

      {% set from_state = from_s.state %}
      {% set to_state   = to_s.state %}

      {# Safe reads: treat missing attributes as 0 #}
      {% set from_b = from_s.attributes.brightness | default(0, true) | int(0) %}
      {% set to_b   = to_s.attributes.brightness   | default(0, true) | int(0) %}
      {% set b_delta = (to_b - from_b) | abs %}

      {% set from_ct = from_s.attributes.color_temp | default(0, true) | int(0) %}
      {% set to_ct   = to_s.attributes.color_temp   | default(0, true) | int(0) %}
      {% set ct_delta = (to_ct - from_ct) | abs %}

      {% set from_h = from_s.attributes.hs_color | default('', true) %}
      {% set to_h   = to_s.attributes.hs_color   | default('', true) %}

      {% set from_mode = from_s.attributes.color_mode | default('', true) %}
      {% set to_mode   = to_s.attributes.color_mode   | default('', true) %}

      {# Thresholds: increase if auto adjustments trigger override #}
      {% set BRIGHTNESS_DELTA_MIN = 8 %}
      {% set CT_DELTA_MIN = 15 %}

      {# Only treat colour changes as meaningful in real colour modes #}
      {% set COLOUR_MODES = ['hs', 'rgb', 'xy'] %}
      {% set meaningful_colour_change =
        (from_mode in COLOUR_MODES or to_mode in COLOUR_MODES) and (from_h != to_h)
      %}

      {% set meaningful_brightness_change = (b_delta >= BRIGHTNESS_DELTA_MIN) %}
      {% set meaningful_ct_change         = (ct_delta >= CT_DELTA_MIN) %}

      {% set turned_off = (from_state == 'on' and to_state == 'off') %}
      {% set turned_on  = (from_state != 'on' and to_state == 'on') %}

      {{
        meaningful_brightness_change
        or meaningful_ct_change
        or meaningful_colour_change
        or turned_off
        or turned_on
      }}

action:
  - service: input_boolean.turn_on
    target:
      entity_id: input_boolean.lounge_manual_override  # <-- CHANGE IF NEEDED

mode: restart
