Help with template switch that will not reset when conditions are not met

Hi I am battling to get ESPhome to switch off this template switch once it has run.

This is for a fish tank water change system, the system has a variety of switches and sensors to control the operation.

My issue is in setting up a template switch which only runs under certain conditions and all is running well except for the fact that the moment I execute the switch to carry out the water change it does not switch off in HA and remains ‘on’. This is irrespective of whether the conditions are met for the water change or not. I have done a fair amount of searching and have tried to change the optimistic setting but then need to switch the switch off manually and I have not been successful in writing this code (im not great at coding).

As the esp is rebooted the state in HA is shown as Off, the moment I activate it it sets to ON and remains ON when it should obviously be set to off once complete.

Any help would be greatly appreciated

The main area of the code is here

  - platform: template
    name: "water change"
    id: water_change
    optimistic: True
    icon: mdi:water-sync
    on_turn_on:
      if:
        condition:
          all:
            - switch.is_off: pump_in
            - switch.is_off: pump_out
            - lambda: |-
                return id(leak_sensor).state < 0.14;
        then:
          - logger.log: "Water Change - Pumping Out"
          - switch.turn_off: filter
          - switch.turn_off: heater
          - switch.turn_on: pump_out
          - delay: !lambda "return (id(pump_out_time).state) * 10000 ;"  
          - switch.turn_off: pump_out
          - switch.turn_on: pump_in
          - logger.log: "Water Change - Pumping In"
          - delay: !lambda "return (id(pump_in_time).state) * 10000 ;"  
          - switch.turn_off: pump_in
          - switch.turn_on: filter
          - switch.turn_on: heater
          - logger.log: "Water Change Complete"
        
        else:
          - switch.turn_off: pump_out
          - switch.turn_off: pump_in
          - switch.turn_off: water_change

It’s only going to shut off if the conditions AREN’T met when you turn it on, is that what you intended? Not fully following what you’re after, but it kind of seems like you just need to turn it off at the end of your ‘then’ sequence.

Thanks Ben, I have modified the code for this now, I just assumed that once complete this would terminate the template, now it works for the situations the conditions are met but oddly not when then are not met, it only turns off the pumps and not the water change template

I have now added a 1s delay before switching the template switch off when the conditions are not met and this seems to work, no clue why but because the ‘met condition’ section had some delays built in I guess this was a next logical step, any better method would be welcome