- sensor:
    - name: "timer_ch_duration"
      state: "{{ (states('input_number.timer_ch') | int * 60) | int }}"
      unit_of_measurement: "seconds"

    - name: "Grocy Chores Weekly"
      unique_id: grocy_chores_weekly
      state: >
        {{ state_attr('sensor.grocy_chores', 'chores')
           | selectattr('period_type', 'equalto', 'weekly')
           | list | count }}
      attributes:
        chores: >
          {{ state_attr('sensor.grocy_chores', 'chores')
             | selectattr('period_type', 'equalto', 'weekly')
             | list }}

    - name: "Grocy Chores Monthly"
      unique_id: grocy_chores_monthly
      state: >
        {{ state_attr('sensor.grocy_chores', 'chores')
           | selectattr('period_type', 'equalto', 'monthly')
           | list | count }}
      attributes:
        chores: >
          {{ state_attr('sensor.grocy_chores', 'chores')
             | selectattr('period_type', 'equalto', 'monthly')
             | list }}

    - name: "Grocy Chores Adaptive"
      unique_id: grocy_chores_adaptive
      state: >
        {{ state_attr('sensor.grocy_chores', 'chores')
           | selectattr('period_type', 'equalto', 'adaptive')
           | list | count }}
      attributes:
        chores: >
          {{ state_attr('sensor.grocy_chores', 'chores')
             | selectattr('period_type', 'equalto', 'adaptive')
             | list }}

    - name: "Lumieres Allumees"
      unique_id: lumieres_allumees
      state: >
        {{ expand('light.lumieres')
           | selectattr('state', 'eq', 'on') | list | count }}
      unit_of_measurement: "allumée(s)"

    - name: "Volets Ouverts"
      unique_id: volets_ouverts
      state: >
        {{ expand('cover.volets')
           | selectattr('state', 'eq', 'open') | list | count }}
      unit_of_measurement: "ouvert(s)"

    - name: "Prises Actives"
      unique_id: prises_actives
      state: >
        {{ expand('switch.prises')
           | selectattr('state', 'eq', 'on') | list | count }}
      unit_of_measurement: "active(s)"

    - name: "Ouvertures Ouvertes"
      unique_id: ouvertures_ouvertes
      state: >
        {{ expand('binary_sensor.ouvrants')
           | selectattr('state', 'eq', 'on') | list | count }}
      unit_of_measurement: "ouvert(s)"

    - name: "Watchman Missing"
      unique_id: watchman_missing
      state: >
        {{ state_attr("sensor.watchman_missing_entities", "entities")
           | selectattr('state', 'eq', 'missing') | list | count }}
      icon: mdi:alert-circle

    - name: "Watchman Unavail"
      unique_id: watchman_unavail
      state: >
        {{ state_attr("sensor.watchman_missing_entities", "entities")
           | selectattr('state', 'eq', 'unavail') | list | count }}
      icon: mdi:alert-circle-outline

    - name: "HACS Intégrations count"
      unique_id: hacs_integrations_count
      state: >
        {{ integration_entities('hacs') | list | count }}
      icon: mdi:package-variant

    - name: "Grocy - Corvées hebdo réalisées"
      unique_id: grocy_weekly_done
      unit_of_measurement: "corvées"
      icon: mdi:check-circle
      state: >
        {% set chores = state_attr('sensor.grocy_chores_weekly', 'chores') %}
        {% if chores %}
          {% set week_start = now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=now().weekday()) %}
          {{ chores | selectattr('last_tracked_time', 'ne', None)
                    | selectattr('last_tracked_time', 'ge', week_start.isoformat())
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Grocy - Corvées hebdo restantes"
      unique_id: grocy_weekly_remaining
      unit_of_measurement: "corvées"
      icon: mdi:clock-alert
      state: >
        {% set chores = state_attr('sensor.grocy_chores_weekly', 'chores') %}
        {% if chores %}
          {% set dow = now().weekday() %}
          {% set days_to_friday = (4 - dow) % 7 %}
          {% set friday_end = (now().replace(hour=23, minute=59, second=59, microsecond=0) + timedelta(days=days_to_friday)).isoformat() %}
          {{ chores | selectattr('next_estimated_execution_time', 'ne', None)
                    | selectattr('next_estimated_execution_time', 'le', friday_end)
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Grocy - Corvées mensuelles réalisées"
      unique_id: grocy_monthly_done
      unit_of_measurement: "corvées"
      icon: mdi:check-circle
      state: >
        {% set chores = state_attr('sensor.grocy_chores_monthly', 'chores') %}
        {% if chores %}
          {% set week_start = now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=now().weekday()) %}
          {{ chores | selectattr('last_tracked_time', 'ne', None)
                    | selectattr('last_tracked_time', 'ge', week_start.isoformat())
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Grocy - Corvées mensuelles restantes"
      unique_id: grocy_monthly_remaining
      unit_of_measurement: "corvées"
      icon: mdi:clock-alert
      state: >
        {% set chores = state_attr('sensor.grocy_chores_monthly', 'chores') %}
        {% if chores %}
          {% set dow = now().weekday() %}
          {% set days_to_friday = (4 - dow) % 7 %}
          {% set friday_end = (now().replace(hour=23, minute=59, second=59, microsecond=0) + timedelta(days=days_to_friday)).isoformat() %}
          {{ chores | selectattr('next_estimated_execution_time', 'ne', None)
                    | selectattr('next_estimated_execution_time', 'le', friday_end)
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Grocy - Corvées adaptatives réalisées"
      unique_id: grocy_adaptive_done
      unit_of_measurement: "corvées"
      icon: mdi:check-circle
      state: >
        {% set chores = state_attr('sensor.grocy_chores_adaptive', 'chores') %}
        {% if chores %}
          {% set week_start = now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=now().weekday()) %}
          {{ chores | selectattr('last_tracked_time', 'ne', None)
                    | selectattr('last_tracked_time', 'ge', week_start.isoformat())
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Grocy - Corvées adaptatives restantes"
      unique_id: grocy_adaptive_remaining
      unit_of_measurement: "corvées"
      icon: mdi:clock-alert
      state: >
        {% set chores = state_attr('sensor.grocy_chores_adaptive', 'chores') %}
        {% if chores %}
          {% set dow = now().weekday() %}
          {% set days_to_friday = (4 - dow) % 7 %}
          {% set friday_end = (now().replace(hour=23, minute=59, second=59, microsecond=0) + timedelta(days=days_to_friday)).isoformat() %}
          {{ chores | selectattr('next_estimated_execution_time', 'ne', None)
                    | selectattr('next_estimated_execution_time', 'le', friday_end)
                    | list | count }}
        {% else %}
          0
        {% endif %}

    - name: "Calendrier Mashome prochain"
      unique_id: calendar_mashome_next
      state: >
        {% set next = state_attr('calendar.mashome', 'start_time') %}
        {% if next %}
          {% set diff = (as_local(as_datetime(next)) - now()).days %}
          {{ diff <= 6 and diff >= 0 }}
        {% else %}
          false
        {% endif %}

    - name: "Calendrier Garbage prochain"
      unique_id: calendar_garbage_next
      state: >
        {% set next = state_attr('calendar.garbage', 'start_time') %}
        {% if next %}
          {% set diff = (as_local(as_datetime(next)) - now()).days %}
          {{ diff <= 6 and diff >= 0 }}
        {% else %}
          false
        {% endif %}

    - name: "Calendrier Garden prochain"
      unique_id: calendar_garden_next
      state: >
        {% set next = state_attr('calendar.garden', 'start_time') %}
        {% if next %}
          {% set diff = (as_local(as_datetime(next)) - now()).days %}
          {{ diff <= 6 and diff >= 0 }}
        {% else %}
          false
        {% endif %}

    - name: "Calendrier Bestioles prochain"
      unique_id: calendar_bestioles_next
      state: >
        {% set next = state_attr('calendar.bestioles', 'start_time') %}
        {% if next %}
          {% set diff = (as_local(as_datetime(next)) - now()).days %}
          {{ diff <= 30 and diff >= 0 }}
        {% else %}
          false
        {% endif %}

- sensor:
    - name: mojo_delai_repas
      unique_id: mojo_delai_repas
      state: >
        {% set last = states.sensor.nutri_mojo_dernier_montant.last_changed %}
        {% set diff = (now() - last).total_seconds() | int %}
        {% set h = (diff // 3600) | int %}
        {% set m = ((diff % 3600) // 60) | int %}
        {% if h == 0 %}il y a {{ m }}min
        {% elif h < 2 %}il y a {{ h }}h{{ '%02d' | format(m) }}
        {% else %}il y a {{ h }}h
        {% endif %}
      attributes:
        secondes: >
          {{ (now() - states.sensor.nutri_mojo_dernier_montant.last_changed).total_seconds() | int }}

    - name: mojo_delai_litiere
      unique_id: mojo_delai_litiere
      state: >
        {% set last = states.counter.compteur_litiere.last_changed %}
        {% set diff = (now() - last).total_seconds() | int %}
        {% set h = (diff // 3600) | int %}
        {% set m = ((diff % 3600) // 60) | int %}
        {% if h == 0 %}il y a {{ m }}min
        {% elif h < 2 %}il y a {{ h }}h{{ '%02d' | format(m) }}
        {% else %}il y a {{ h }}h
        {% endif %}
      attributes:
        secondes: >
          {{ (now() - states.counter.compteur_litiere.last_changed).total_seconds() | int }}

    - name: mojo_indice_confort
      unique_id: mojo_indice_confort
      unit_of_measurement: "/10"
      state: >
        {% set seuil = states('input_number.seuil_nettoyage_litiere') | float %}
        {% set passages = states('counter.compteur_litiere') | int %}
        {% set delai_repas = (now() - states.sensor.nutri_mojo_dernier_montant.last_changed).total_seconds() / 3600 %}
        {% set score_litiere = [10 - ((passages / seuil) * 10) | round(0), 0] | max %}
        {% set score_repas = [10 - ((delai_repas / 8) * 10) | round(0), 0] | max %}
        {{ ((score_litiere * 0.5) + (score_repas * 0.5)) | round(1) }}

    - name: mojo_humeur
      unique_id: mojo_humeur
      state: >
        {% set seuil = states('input_number.seuil_nettoyage_litiere') | float %}
        {% set passages = states('counter.compteur_litiere') | int %}
        {% set delai_repas = (now() - states.sensor.nutri_mojo_dernier_montant.last_changed).total_seconds() / 3600 %}
        {% set litiere_ok = passages < seuil * 0.5 %}
        {% set litiere_sale = passages > seuil * 0.8 %}
        {% set repas_recent = delai_repas < 2 %}
        {% set affame = delai_repas > 6 %}
        {% if affame and litiere_sale %}Affamé et en colère
        {% elif affame %}Affamé
        {% elif litiere_sale %}Grognon
        {% elif repas_recent and litiere_ok %}Roi du monde
        {% elif repas_recent %}Content
        {% else %}Neutre
        {% endif %}
      attributes:
        icone: >
          {% set h = states('sensor.mojo_humeur') %}
          {% if h == 'Affamé et en colère' %}😾🍽️
          {% elif h == 'Affamé' %}🍽️😿
          {% elif h == 'Grognon' %}😾
          {% elif h == 'Roi du monde' %}👑😸
          {% elif h == 'Content' %}😸
          {% else %}🐱
          {% endif %}
        citation: >
          {% set h = states('sensor.mojo_humeur') %}
          {% if h == 'Affamé et en colère' %}Tu pourrais faire un effort sur les deux fronts non ?!
          {% elif h == 'Affamé' %}Je vois des croquettes partout... des croquettes imaginaires...
          {% elif h == 'Grognon' %}Cette litière est une insulte à ma dignité féline.
          {% elif h == 'Roi du monde' %}La vie est belle. Je règne sur tout ce que je vois.
          {% elif h == 'Content' %}Zzz... bien mangé, bien fait... zzz...
          {% else %}J'observe. J'attends. Je suis un chat.
          {% endif %}

    - name: mojo_barre_faim
      unique_id: mojo_barre_faim
      unit_of_measurement: "%"
      state: >
        {% set repas_s = state_attr('sensor.mojo_delai_repas', 'secondes') | int(0) %}
        {{ [[((1 - repas_s / 28800) * 100) | round, 0] | max, 100] | min }}

    - name: mojo_barre_hygiene
      unique_id: mojo_barre_hygiene
      unit_of_measurement: "%"
      state: >
        {% set passages = states('counter.compteur_litiere') | int %}
        {% set seuil = states('input_number.seuil_nettoyage_litiere') | float(10) %}
        {{ [[((1 - passages / seuil) * 100) | round, 0] | max, 100] | min }}

    - name: mojo_barre_energie
      unique_id: mojo_barre_energie
      unit_of_measurement: "%"
      state: >
        {% set h = now().hour %}
        {% if h >= 6 and h <= 9 %}90
        {% elif h >= 17 and h <= 20 %}85
        {% elif h >= 13 and h <= 15 %}15
        {% elif h >= 22 or h < 5 %}10
        {% else %}55{% endif %}

    - name: mojo_barre_calins
      unique_id: mojo_barre_calins
      unit_of_measurement: "%"
      state: >
        {{ ((now().minute * 7 + now().hour * 13) % 50) + 30 }}

    - name: mojo_barre_capteur
      unique_id: mojo_barre_capteur
      unit_of_measurement: "%"
      state: >
        {% set b = states('sensor.litiere_etat_batterie') %}
        {% if b == 'high' %}90
        {% elif b == 'middle' %}50
        {% elif b == 'low' %}15
        {% else %}0{% endif %}
