blueprint:
  name: TV — YouTube show button
  description: >-
    Press a Zigbee button to play the next episode of a YouTube
    "show" — a curated list of YouTube video IDs that loop. If the
    Cast session is currently paused, pressing the button resumes
    instead of advancing.


    Each YouTube show in the colour-coded TV setup has its own copy of
    this blueprint, plus a paired auto-advance blueprint
    (tv-youtube-auto-advance) so the next video plays automatically
    when the current one finishes.


    What it does on each press:

    1. If the Cast is paused → resume (preserves the watching position).

    2. Otherwise:
       - Mark this show as "current" in the input_select helper (so
         auto-advance picks the right playlist).
       - Wake the TV if it's off and switch to the HDMI source.
       - Increment the playlist index modulo the playlist length.
       - Close the current Cast session, wait briefly, and play the
         next video.


    Helpers needed (create these once before importing — see the
    setup guide):

    - One input_select named "current_show" with one option per show
      button (e.g. doc_martin / mr_bean / bgt).

    - One input_number per show, used as the rotating playlist index
      (range 0–N, step 1, no unit).


    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-youtube-show-button.yaml

  input:
    button_device:
      name: Zigbee button
      description: The Zigbee button that triggers this show.
      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).
      selector:
        entity:
          domain: media_player

    webos_tv:
      name: LG WebOS TV
      description: >-
        The LG WebOS TV media player entity (used to detect TV power
        state and to switch HDMI source).
      selector:
        entity:
          domain: media_player

    tv_remote:
      name: Android TV Remote
      description: >-
        The Android TV Remote entity for the dongle. Used to wake the
        TV via CEC when it's off.
      selector:
        entity:
          domain: remote

    hdmi_source_name:
      name: HDMI source name on the TV
      description: >-
        The exact source name the LG TV uses for the HDMI port the
        Cast dongle is on.
      default: Living room TV
      selector:
        text:

    current_show_helper:
      name: "current_show input_select helper"
      description: >-
        The input_select helper that tracks which show is currently
        playing. Same helper is used for all show buttons; this
        blueprint sets it to the option you specify next.
      selector:
        entity:
          domain: input_select

    this_show_option:
      name: This show's option
      description: >-
        The option name (in the input_select above) that represents
        this show. Must be lowercase, no spaces (e.g. doc_martin,
        mr_bean, bgt).
      selector:
        text:

    playlist_index_helper:
      name: Playlist index helper (input_number)
      description: >-
        A dedicated input_number helper for this show that tracks
        the rotating position in the playlist.
      selector:
        entity:
          domain: input_number

    playlist_video_ids:
      name: Playlist of YouTube video IDs
      description: >-
        One YouTube video ID per line. The 11-character ID from the
        URL (the bit after watch?v=). Blank lines are ignored.
      selector:
        text:
          multiline: true

    wake_timeout:
      name: TV wake timeout (seconds)
      description: >-
        How long to wait for the TV to come on after CEC wake before
        giving up and continuing anyway.
      default: 15
      selector:
        number:
          min: 5
          max: 60
          step: 1
          unit_of_measurement: seconds
          mode: slider

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

variables:
  cast_entity: !input cast_media_player
  webos_entity: !input webos_tv
  remote_entity: !input tv_remote
  source_name: !input hdmi_source_name
  current_show_entity: !input current_show_helper
  show_option: !input this_show_option
  idx_entity: !input playlist_index_helper
  playlist_raw: !input playlist_video_ids

action:

  - choose:

      # ── Branch 1: Cast is paused → resume ────────────────────────
      - alias: Resume if paused
        conditions:
          - condition: state
            entity_id: !input cast_media_player
            state: paused
        sequence:
          - choose:
              - conditions:
                  - condition: state
                    entity_id: !input webos_tv
                    state: 'on'
                sequence: []
            default:
              - service: remote.turn_on
                target:
                  entity_id: !input tv_remote
              - wait_for_trigger:
                  - platform: state
                    entity_id: !input webos_tv
                    to: 'on'
                timeout:
                  seconds: !input wake_timeout
                continue_on_timeout: true
          - service: media_player.select_source
            target:
              entity_id: !input webos_tv
            data:
              source: !input hdmi_source_name
            continue_on_error: true
          - service: media_player.media_play
            target:
              entity_id: !input cast_media_player

    # ── Branch 2 (default): advance and play next video ─────────────
    default:

      # 1. Mark this show as "current" so auto-advance picks the right
      #    playlist when the next video ends.
      - service: input_select.select_option
        target:
          entity_id: !input current_show_helper
        data:
          option: !input this_show_option

      # 2. Ensure the TV is on (CEC wake if needed).
      - choose:
          - conditions:
              - condition: state
                entity_id: !input webos_tv
                state: 'on'
            sequence: []
        default:
          - service: remote.turn_on
            target:
              entity_id: !input tv_remote
          - wait_for_trigger:
              - platform: state
                entity_id: !input webos_tv
                to: 'on'
            timeout:
              seconds: !input wake_timeout
            continue_on_timeout: true
          - delay:
              seconds: 2

      # 3. Switch to the HDMI input the Cast dongle is on (needed in
      #    case we're coming from Live TV / news).
      - service: media_player.select_source
        target:
          entity_id: !input webos_tv
        data:
          source: !input hdmi_source_name

      # 4. Increment the playlist index modulo the playlist length.
      - service: input_number.set_value
        target:
          entity_id: !input playlist_index_helper
        data:
          value: >-
            {% set ids = playlist_raw.replace('\r', '').split('\n')
                         | map('trim') | reject('equalto', '') | list -%}
            {{ (states(idx_entity) | int(0) + 1) % (ids | length) }}

      # 5. Close the current Cast session — fixes the "stale Cast
      #    silently ignores commands" gotcha.
      - service: media_player.turn_off
        target:
          entity_id: !input cast_media_player
        continue_on_error: true

      # 6. Brief grace period before re-casting.
      - delay:
          seconds: 3

      # 7. Cast the next video in the playlist.
      - service: media_player.play_media
        target:
          entity_id: !input cast_media_player
        data:
          media_content_type: cast
          media_content_id: >-
            {% set ids = playlist_raw.replace('\r', '').split('\n')
                         | map('trim') | reject('equalto', '') | list -%}
            {% set idx = states(idx_entity) | int(0) % (ids | length) -%}
            {{ {'app_name': 'youtube', 'media_id': ids[idx]} | tojson }}
