blueprint:
  name: TV — Off button
  description: >-
    Press a Zigbee button to pause any playing Cast media and turn the TV
    off. Pause-then-power means video position is preserved on the Cast
    session, so a "play" button can resume later.


    Listens for all Third Reality button command variants
    (short_press / single / on / long_press / hold) so it works
    regardless of the button's firmware quirks.


    Recommended hardware: Third Reality 3RSB22BZ Zigbee buttons + an
    LG WebOS TV. Part of the colour-coded TV button setup at
    https://remindmevoice.com/guide/simple-tv-buttons.

  domain: automation
  source_url: https://remindmevoice.com/blueprints/tv-off-button.yaml

  input:
    button_device:
      name: Zigbee button
      description: >-
        The Zigbee button that triggers TV off. Pair it via ZHA first
        (Settings → Devices &amp; Services → ZHA → + Add Device).
      selector:
        device:
          integration: zha

    cast_media_player:
      name: TV Cast media player
      description: >-
        The Google Cast / Chromecast media player on the TV
        (e.g. media_player.living_room_tv). Used to pause whatever's
        currently playing before turning the TV off.
      selector:
        entity:
          domain: media_player

    webos_tv:
      name: LG WebOS TV
      description: >-
        The LG WebOS TV media player entity
        (e.g. media_player.lg_webos_tv). Used to send the POWER button.
      selector:
        entity:
          domain: media_player

mode: single
max_exceeded: silent

trigger:
  - platform: event
    event_type: zha_event
    event_data:
      device_id: !input button_device
      command: remote_button_short_press
  - platform: event
    event_type: zha_event
    event_data:
      device_id: !input button_device
      command: single
  - platform: event
    event_type: zha_event
    event_data:
      device_id: !input button_device
      command: 'on'
  - platform: event
    event_type: zha_event
    event_data:
      device_id: !input button_device
      command: remote_button_long_press
  - platform: event
    event_type: zha_event
    event_data:
      device_id: !input button_device
      command: hold

action:

  # 1. Pause the Cast session so video position is preserved.
  #    continue_on_error: nothing playing should not block the TV-off step.
  - service: media_player.media_pause
    target:
      entity_id: !input cast_media_player
    continue_on_error: true

  # 2. Brief pause to let the pause take effect before powering off.
  - delay:
      seconds: 1

  # 3. Send the POWER button via the WebOS API. Reliable standby for LG TVs.
  - service: webostv.button
    data:
      entity_id: !input webos_tv
      button: POWER
