blueprint:
  name: APA PsycTests Live Counter (AWTRIX 3)
  description: Keeps APA PsycTests counter as persistent AWTRIX app
  domain: automation

trigger:
  - platform: time_pattern
    minutes: "/30"

variables:
  url: "https://www.apa.org/pubs/databases/psyctests"
  mqtt_topic: "awtrix/custom/apa_counter"

action:
  - service: http.get
    data:
      url: "{{ url }}"
    response_variable: page

  - variables:
      value: >
        {{ page.content | regex_findall_index('([0-9,]+) records', 0) }}

  - service: input_text.set_value
    data:
      entity_id: input_text.apa_last_value
      value: "{{ value }}"

  - choose:
      - conditions:
          - condition: template
            value_template: "{{ value != states('input_text.apa_last_value') }}"
        sequence:
          - service: mqtt.publish
            data:
              topic: "{{ mqtt_topic }}"
              payload: >
                {
                  "id": "apa_counter",
                  "text": "{{ value }} records in APA PsycTests",
                  "icon": 75782,
                  "rainbow": true
                }

      - default:
          - service: mqtt.publish
            data:
              topic: "{{ mqtt_topic }}"
              payload: >
                {
                  "id": "apa_counter",
                  "text": "{{ value }} records in APA PsycTests",
                  "icon": 75782,
                  "rainbow": true
                }