- alias: Tesla smart charging PRO
  id: tesla_smart_charging_pro
  mode: restart

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

    - platform: time_pattern
      minutes: "0"

  condition:
    - condition: state
      entity_id: input_boolean.tesla_manual_override
      state: "off"

    - condition: template
      value_template: >
        {% set deadline = states('input_datetime.tesla_charge_deadline') %}
        {{ deadline not in ['unknown','unavailable',''] and as_timestamp(deadline) > as_timestamp(now()) }}

    - condition: state
      entity_id: binary_sensor.snowywhite_charger
      state: "on"

  action:
    - variables:
        should_charge: "{{ is_state('binary_sensor.tesla_charge_now','on') }}"
        currently_charging: "{{ is_state('switch.home_charging', 'on') }}"
        last_start: "{{ states('input_datetime.tesla_last_start') }}"
        last_start_ts: >
          {% if last_start not in ['unknown','unavailable',''] %}
            {{ as_timestamp(last_start) }}
          {% else %}
            0
          {% endif %}
        runtime: "{{ as_timestamp(now()) - last_start_ts }}"

    - choose:

        # -------------------------
        # START CHARGING
        # -------------------------
        - conditions:
            - condition: template
              value_template: "{{ should_charge }}"
          sequence:
            - if:
                - condition: template
                  value_template: "{{ not currently_charging }}"
              then:
                - service: input_datetime.set_datetime
                  target:
                    entity_id: input_datetime.tesla_last_start
                  data:
                    datetime: "{{ now().isoformat() }}"

                - service: switch.turn_on
                  target:
                    entity_id: switch.home_charging

        # -------------------------
        # STOP CHARGING (med hysterese)
        # -------------------------
        - conditions:
            - condition: template
              value_template: "{{ currently_charging and not should_charge and runtime > 3600 }}"
          sequence:
            - service: switch.turn_off
              target:
                entity_id: switch.home_charging

- alias: "Tesla - nulstil manuel override ved frakobling"
  id: tesla_reset_manual_override
  trigger:
    - platform: state
      entity_id: binary_sensor.snowywhite_charger
      to: "off"
  action:
    - service: input_boolean.turn_off
      target:
        entity_id: input_boolean.tesla_manual_override
