blueprint:
  name: "The Big Board Election Watch Party Lights & Announcements"
  description: >
    Flashes smart RGB lights and broadcasts voice announcements when The Big Board
    declares an election victory or party flip. Integrates with the election-watcher
    unified MQTT event stream.
  domain: automation
  input:
    target_lights:
      name: "Party RGB Lights"
      description: "RGB or color-temperature smart lights to flash during election victory events."
      selector:
        target:
          entity:
            domain: light
    mqtt_events_topic:
      name: "MQTT Events Topic"
      description: "Unified MQTT topic published by The Big Board microservice."
      default: "homelab/elections/events"
      selector:
        text: {}
    announcement_media_player:
      name: "TTS Announcement Speaker (Optional)"
      description: "Media player (Sonos, Nest, Echo, HomePod) for voice race announcements."
      default: {}
      selector:
        target:
          entity:
            domain: media_player
    tts_engine:
      name: "Text-to-Speech Engine (Optional)"
      description: "TTS engine entity for voice synthesis (e.g. tts.google_en_com, tts.piper, or tts.cloud)."
      default: ""
      selector:
        entity:
          domain: tts
    dem_color:
      name: "Democratic Victory Color (RGB)"
      description: "Color to flash when Democratic candidates win or flip a seat."
      default: [0, 80, 255]
      selector:
        color_rgb: {}
    rep_color:
      name: "Republican Victory Color (RGB)"
      description: "Color to flash when Republican candidates win or flip a seat."
      default: [220, 38, 38]
      selector:
        color_rgb: {}
    other_color:
      name: "Independent / Other Color (RGB)"
      description: "Color to flash when Independent or third-party candidates win."
      default: [245, 158, 11]
      selector:
        color_rgb: {}
    flash_count:
      name: "Flash Pulse Count"
      description: "Number of light pulses during the celebration."
      default: 4
      selector:
        number:
          min: 1
          max: 15
          step: 1
          unit_of_measurement: "pulses"
    restore_lights:
      name: "Restore Previous Light State"
      description: "Return lights to their previous brightness, color, and power state after the event."
      default: true
      selector:
        boolean: {}

mode: queued
max: 10

trigger:
  - platform: mqtt
    topic: !input mqtt_events_topic

condition:
  - condition: template
    value_template: "{{ trigger.payload_json.event_type in ['call', 'flip'] }}"

action:
  - variables:
      event: "{{ trigger.payload_json }}"
      target_lights: !input target_lights
      target_speaker: !input announcement_media_player
      tts_engine_entity: !input tts_engine
      restore_enabled: !input restore_lights
      pulse_count: !input flash_count
      party: "{{ (event.winner_party or event.leader_party or '') | upper }}"
      color_dem: !input dem_color
      color_rep: !input rep_color
      color_other: !input other_color
      event_color: >
        {% if party in ['DEM', 'DEMOCRAT', 'DEMOCRATIC'] %}
          {{ color_dem }}
        {% elif party in ['REP', 'REPUBLICAN', 'GOP'] %}
          {{ color_rep }}
        {% else %}
          {{ color_other }}
        {% endif %}
      voice_message: >
        {% if event.event_type == 'flip' %}
          Election Alert: Seat Flip! In {{ event.title }}, {{ event.winner_name }} has flipped this seat to the {{ party }} party!
        {% else %}
          Election Call: {{ event.title }} has been called for {{ event.winner_name }}, {{ party }}!
        {% endif %}

  # Step 1: Snapshot current light state if restore is enabled and not already running in queue
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ restore_enabled and target_lights != {} and this.attributes.current | default(1) <= 1 }}"
        sequence:
          - service: scene.create
            data:
              scene_id: election_lights_before_party
              snapshot_entities: >
                {{ expand(target_lights.entity_id | default([], true))
                   | selectattr('domain', 'eq', 'light')
                   | map(attribute='entity_id')
                   | list }}

  # Step 2: Parallel voice announcement if speaker and TTS engine configured
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ target_speaker != {} and tts_engine_entity != '' }}"
        sequence:
          - service: tts.speak
            target:
              entity_id: !input tts_engine
            data:
              media_player_entity_id: >
                {{ target_speaker.entity_id if target_speaker.entity_id is defined else target_speaker }}
              message: "{{ voice_message }}"

  # Step 3: Flash lights with winner party color
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ target_lights != {} }}"
        sequence:
          - repeat:
              count: "{{ pulse_count }}"
              sequence:
                - service: light.turn_on
                  target: !input target_lights
                  data:
                    rgb_color: "{{ event_color }}"
                    brightness: 255
                    transition: 0.2
                - delay:
                    milliseconds: 800
                - service: light.turn_off
                  target: !input target_lights
                  data:
                    transition: 0.2
                - delay:
                    milliseconds: 400

  # Step 4: Restore previous light state once queue is draining
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ restore_enabled and target_lights != {} and this.attributes.current | default(1) <= 1 }}"
        sequence:
          - service: scene.apply
            data:
              scene_id: scene.election_lights_before_party
