# =====================================================================
# 3D-DRUCK - HISTORIE
# Start wird bei "laeuft" gemerkt; beim Ende wird ein Datensatz erzeugt.
# Historie liegt als JSON im Attribut "history", neuester Eintrag zuerst.
# =====================================================================

- trigger:
    - platform: state
      entity_id: binary_sensor.3d_druck_lauft
      to: "on"
      id: start
    - platform: state
      entity_id: binary_sensor.3d_druck_lauft
      to: "off"
      id: end

  sensor:
    - name: "3D Drucker: Historie"
      unique_id: 3d_druck_history
      icon: mdi:history
      state: >
        {% set hist = (this.attributes.history | default('[]')) | from_json %}
        {{ hist | length }}
      attributes:
        current_start: >
          {% if trigger.id == 'start' %}
            {{ now().isoformat() }}
          {% else %}
            {{ this.attributes.current_start if this.attributes.current_start is not none else '' }}
          {% endif %}
        history: >
          {% set max_items = 20 %}
          {% set prev = (this.attributes.history | default('[]')) | from_json %}
          {% if trigger.id == 'end' %}
            {% set name_ent = 'sensor.bambulab_p1s_name_der_aufgabe' %}
            {% set start_ent = 'sensor.bambulab_p1s_startzeit' %}
            {% set plan_end_e = 'sensor.bambulab_p1s_vrs_fertigstellung' %}
            {% set weight_ent = 'sensor.bambulab_p1s_gewicht_des_drucks' %}
            {% set has_name = states(name_ent) not in ['unknown','unavailable',''] %}
            {% set has_start = states(start_ent) not in ['unknown','unavailable',''] %}
            {% set has_plend = states(plan_end_e) not in ['unknown','unavailable',''] %}
            {% set has_weight = states(weight_ent) not in ['unknown','unavailable',''] %}
            {% set job_name = states(name_ent) if has_name else 'BambuLab Druckjob' %}
            {% set started_at = states(start_ent) if has_start else (this.attributes.current_start or now().isoformat()) %}
            {% set planned_end = states(plan_end_e) if has_plend else '' %}
            {% set weight_g = (states(weight_ent) | float(0)) if has_weight else 0 %}
            {% set kwh = (states('sensor.3d_drucker_energy_druck') | float(0)) | round(3) %}
            {% set preis = states('input_number.aktueller_strompreis') | float(0) %}
            {% set cost = (kwh * preis) | round(2) %}
            {% set s = as_datetime(started_at) %}
            {% set e = now() %}
            {% set dur = (as_timestamp(e) - as_timestamp(s)) | int(0) %}
            {% set new = [{
              "name": job_name,
              "started_at": s.isoformat(),
              "ended_at": e.isoformat(),
              "duration_sec": dur,
              "kwh": kwh,
              "cost": cost,
              "planned_end": planned_end,
              "weight_g": weight_g
            }] %}
            {{ (new + prev)[:max_items] | tojson }}
          {% else %}
            {{ prev | tojson }}
          {% endif %}
