Automation help with trigger dependent on 2 states please

I’m struggling to work out how to trigger an automation that depends on the change of state of one entitiy but only if another entitiy is in a certain state when the first changes. Specifically I’ve got entities monitoring the state of 2 pumps in my ecodan ASHP set-up. Pump1 circulates the heating fluid from the HP, pump2 is for the UFH. When pump 1 is on but 2 is off, the system is in hot water mode. I want to trigger an automation when hot water mode ends, ie pump2 must be off when pump1 changes from on to off. As both are updated simultaneously I can’t use ‘condition’ as both go off together at the end of a heating cycle.
The attempt below uses another sensor that is set by the pump1/pump2 status but I don’t like its specific reference to a number that I happen to know, rather than being an enitity.
So my automation is:

alias: HW cycle end
description: Update HW energy estimate at and of hot water cycle
  - platform: state
      - sensor.hp_waterpump1status
    from: "1"
    to: "0"
  - service: input_number.set_value
      value: >-
        {{ states('input_number.hw_test') | float +
        states('sensor.shellyem_244cab419108_channel_2_energy') | float }}
      entity_id: input_number.hw_test
  - service: input_number.set_value
      value: >-
        {{ states('input_number.hw_out') | float +
        states('sensor.hp_output_by_flowdT') | float }}
      entity_id: input_number.hw_out
mode: single
  - condition: numeric_state
    entity_id: sensor.hp_flow_rate_now
    value_template: ""
    below: 17

which depends on the template sensor:

    - name: HP flow rate now
      state: "{{ states('sensor.HP_WaterPump1Status')|float * states('input_number.flow_rate_hw')|float + states('sensor.HP_WaterPump2Status')|float * (states('input_number.flow_rate_htg')|float - states('input_number.flow_rate_hw')|float) }}"
      unit_of_measurement: l/min
      unique_id: HP_flow_rate_now

which is all very inelegant and I doubt it will work (I haven’t tested it in anger yet as it only triggers once a day).