Script loop better solution - heating control for TRV

I could do with a little help/logic solution to this.
I call this via a trigger from heating radiator valves (TRV) so when they detect a change in state they’ll call this script. The script then loops through all the TRVs and will check if any are below their target temperature. If they are then set an input_boolean (which in turn is then checked using a timer automation and if its on for longer than a set amount of time (to avoid hysteresis) then activate the heating pump to supply heat.

Here is my script currently:

mode: single
icon: mdi:heating-coil
alias: radiator-autoboost
  - service: input_boolean.turn_off
      entity_id: input_boolean.radiator_autoboost
    data: {}
  - repeat:
      for_each: >-
        {{ states.climate | selectattr('attributes.pi_heating_demand',
        'defined') | selectattr('attributes.pi_heating_demand', '>=', 55) |
        map(attribute='entity_id') | list }}
        - service: logbook.log
            name: radiator-valuecheck
            message: "{{ repeat.item }} pi value: "
        - service: input_boolean.turn_on
            entity_id: input_boolean.radiator_autoboost
          data: {}

The problem is I have to set the input_boolean.radiator_autoboost to off at the start of the script, so I am always resetting the state (so I can’t check the state last changed as it’s triggered constantly).
I can’t use variables as due to variable scope the for_each loop would not allow me to query that state outside the loop and set it there, so is there another way of achieving what I’m trying to do here?