blueprint:
  name: "HT Apply Calendar"
  description: >
    Sélectionnez uniquement le Calendrier.
    La zone est déduite du nom du calendrier (ex: calendar.ht_room_calendar -> zone = room).
    Le blueprint lit la description de l'événement actif avec le format :
      In : 22
      Out : 19
    puis applique :
      comfort_temp = In
      eco_temp = Out
  domain: automation

  input:
    calendar_entity:
      name: "Calendrier"
      description: "L'entité pivot (ex: calendar.ht_room_calendar)"
      selector:
        entity:
          domain: calendar

variables:
  calendar_id: !input calendar_entity

  # Pour 'calendar.ht_room_calendar'
  # split('_') => ['calendar.ht', 'room', 'calendar']
  zone: "{{ calendar_id.split('_')[1] }}"

  vtherm_id: "climate.ht_{{ zone }}_vtherm"
  comfort_temp_id: "number.ht_{{ zone }}_vtherm_preset_comfort_temp"
  eco_temp_id: "number.ht_{{ zone }}_vtherm_preset_eco_temp"

trigger:
  - trigger: state
    entity_id: !input calendar_entity
    to:
      - "off"
      - "on"
    for:
      seconds: 5

condition:
  - condition: state
    entity_id: !input calendar_entity
    state: "on"

action:
  - variables:
      raw_desc: "{{ state_attr(calendar_id, 'description') | default('', true) }}"

      # Extraction "In : xx"
      in_str: >-
        {% set txt = raw_desc | replace(',', '.') %}
        {% set m = txt | regex_findall('(?im)^\\s*In\\s*:\\s*([0-9]+(?:\\.[0-9]+)?)\\s*$') %}
        {{ m[0] if m | count > 0 else '' }}

      # Extraction "Out : xx"
      out_str: >-
        {% set txt = raw_desc | replace(',', '.') %}
        {% set m = txt | regex_findall('(?im)^\\s*Out\\s*:\\s*([0-9]+(?:\\.[0-9]+)?)\\s*$') %}
        {{ m[0] if m | count > 0 else '' }}

      in_temp: "{{ in_str | float(0) }}"
      out_temp: "{{ out_str | float(0) }}"

      parsing_ok: "{{ in_str != '' and out_str != '' }}"

      min_vtherm: "{{ state_attr(vtherm_id, 'min_temp') | float(5) }}"
      max_vtherm: "{{ state_attr(vtherm_id, 'max_temp') | float(35) }}"

      comfort_temp: "{{ [[in_temp, min_vtherm] | max, max_vtherm] | min }}"
      eco_temp: "{{ [[out_temp, min_vtherm] | max, max_vtherm] | min }}"

  - condition: template
    value_template: "{{ parsing_ok }}"

  - action: number.set_value
    target:
      entity_id: "{{ comfort_temp_id }}"
    data:
      value: "{{ comfort_temp }}"

  - action: number.set_value
    target:
      entity_id: "{{ eco_temp_id }}"
    data:
      value: "{{ eco_temp }}"

mode: restart