Intelligent Area Toggle

I had some problems trying to toggle all lights in an area in an “intelligent” manner, like the group switch within Lovelace.
By that I mean turn all lights off if any or all lights are on, otherwise turn them all on.
Thought about choosing the specific entities but I think I came up with a better way with the following script (Home Assistant Script For Intelligent Toggle: If any or all lights in an area are on, turns all lights in that area off, else turn them all on. · GitHub):

intelligent_toggle:
  alias: Intelligent Toggle
  fields:
    target_area:
      name: Target Area
      description: "The area to toggle"
      example: "downstairs"
  sequence:
  - if:
    - condition: template
      value_template: |
        {% set ns = namespace(out=false) %}
        {% set ns.out = false %}
        {% set target_area_l = target_area | lower %}
        {%- for state in states if not ns.out-%}
        {%- set entity=state.entity_id-%}
        {%- set area=area_name(state.entity_id)|lower-%}
        {%- set domain=state.domain-%}
        {% if area==target_area_l and domain=="light" and states(entity) == "on"%}
        {% set ns.out = true %}
        {% endif %}
        {%- endfor -%}
        {{ns.out}}
    then:
    - service: light.turn_off
      data: {}
      target:
        area_id: '{{target_area|lower}}'
    else:
    - service: light.turn_on
      data: {}
      target:
        area_id: '{{target_area|lower}}'
  mode: single

Seems to work. Let me know if this is useful for you, or if there are improvements to be made/issues with it’s implementation: I’m new to Home Assistant!

I guess one thing that confused me is that the light.turn_* services expect the area_id to be lower case, whilst it is returned capitalised from the area_name(state.entity_id) . Sprinkling of | lower made this robust, but is that right? How should i understand the capitalisation of areas?

This is again this “make HA beautiful, but don’t mind the function”.
Yeah entities are lower case and most states are lower case but still they are sometimes presented as normal case.
But | lower is correct and shouldn’t cause any issues.