Catch Spotify interrupted because of streaming started on other device

We have multiple Chromecast devices that are connected to a single Spotify account, which mostly works well. However, there are instances when the music gets interrupted because someone started playing on another device. Although not a big problem, it can be annoying. To mitigate this, we have an alternative solution of playing music from our local Plex server, which eliminates the interruption issue. I have explored creating an automation that detects Spotify interruption caused by another device’s playback and replaces it with music from our local Plex server.
I built this automation with the help of ChatGPT, which has proven to be efficient in using jinja2 templates.

Feel free to re-use/comment.

alias: Spotify double usage interruption
description: Detect if Spotify is launched while it was already playing on another device
  - platform: state
      - media_player.audio_chromecast
      - media_player.hub
      - media_player.chromecast
      - media_player.nest_wifi
    to: playing
  - condition: template
    value_template: "{{ (state_attr(trigger.entity_id, 'app_name')) == 'Spotify' }}"
    enabled: true
  - service: media_player.play_media
      entity_id: >
        {% set media_players = states | selectattr("entity_id", "match", "^media_player.*") | list %} 
        {% set playing_media_players = media_players | selectattr('state','in',['playing','paused']) | list %}
        {% set other_playing_media_players = playing_media_players | rejectattr("entity_id", "in",trigger.entity_id)  | rejectattr("entity_id", "match","^media_player.mass*") | list %} 
        {% set other_playing_media_players_spotify = other_playing_media_players | selectattr("attributes.app_name", "eq", "Spotify") | list %} 
        {% for device in other_playing_media_players_spotify %}
        {% endfor %}
      media_content_id: >-
        plex://{ "playlist_name": "{{states('input_select.PlexPlaylist')}}",
        "shuffle": "1" }
      media_content_type: PLAYLIST
mode: single