##########################################################################################
# heat_pump_master_bedroom_helpers.yaml
#
# Master Bedroom Panasonic Comfort Cloud Heat Pump Helpers
#
# Combines:
# - Setpoint helpers (optimistic cloud control)
# - HVAC mode helpers (Off / Heat / Cool / Dry)
# - Profile logic (Normal / Boost / Quiet)
# - Sleep timer system
# - Sync automations
#
# Designed for:
# climate.master_bedroom (Panasonic Comfort Cloud)
#
##########################################################################################

##########################################################################################
# TIMER (Sleep Timer Entity)
##########################################################################################

timer:
  master_bedroom_climate_timer:
    name: Master Bedroom Climate Timer
    duration: "00:00:00"

##########################################################################################
# INPUT HELPERS
##########################################################################################

input_select:
  # Sleep timer dropdown
  master_bedroom_climate_timer_duration:
    name: Master Bedroom Aircon Sleep
    options:
      - "1 hour"
      - "2 hours"
      - "3 hours"
      - "6 hours"
      - "Cancel timer"
    initial: "Cancel timer"
    icon: mdi:timer-outline

  # Optimistic requested HVAC mode (used by dashboard buttons)
  master_bedroom_hvac_requested_mode:
    name: Master Bedroom HVAC Requested Mode
    options:
      - "none"
      - "off"
      - "heat"
      - "cool"
      - "dry"
    initial: "none"

  # Heat pump profile selector
  master_bedroom_heat_pump_profile:
    name: Master Bedroom Heat Pump Profile
    options:
      - Normal
      - Boost
      - Quiet
    initial: Normal

input_number:
  # Optimistic UI setpoint helper
  master_bedroom_setpoint_ui:
    name: Master Bedroom Setpoint UI
    min: 10
    max: 30
    step: 0.5
    mode: box
    unit_of_measurement: "°C"
    icon: mdi:thermometer

##########################################################################################
# TEMPLATE SENSORS
##########################################################################################

template:
  ############################################################################
  # Sleep Timer Remaining (HH:MM display)
  ############################################################################
  - trigger:
      - platform: time_pattern
        minutes: "/1"

      - platform: state
        entity_id:
          - timer.master_bedroom_climate_timer
          - input_select.master_bedroom_climate_timer_duration

    sensor:
      - name: "Master Bedroom Climate Timer Remaining"
        unique_id: master_bedroom_climate_timer_remaining
        icon: mdi:timer
        state: >-
          {% set st = states('timer.master_bedroom_climate_timer') | lower %}
          {% if st == 'idle' %}
            0:00
          {% else %}
            {% set fa = state_attr('timer.master_bedroom_climate_timer', 'finishes_at') %}
            {% if fa %}
              {% set end = as_datetime(fa) %}
              {% set sec = (end - now()).total_seconds() | int(0) %}
              {% if sec < 0 %}{% set sec = 0 %}{% endif %}
              {% set hh = (sec // 3600) | int %}
              {% set mm = ((sec % 3600) // 60) | int %}
              {{ hh }}:{{ '%02d' | format(mm) }}
            {% else %}
              0:00
            {% endif %}
          {% endif %}

  ############################################################################
  # Profile tile sensor (for dashboard icon)
  ############################################################################
  - sensor:
      - name: Master Bedroom Heat Pump Profile Tile
        unique_id: master_bedroom_heat_pump_profile_tile
        state: "{{ states('input_select.master_bedroom_heat_pump_profile') }}"
        icon: >
          {% set p = states('input_select.master_bedroom_heat_pump_profile') %}
          {% if p == 'Boost' %}
            mdi:rocket-launch
          {% elif p == 'Quiet' %}
            mdi:leaf
          {% else %}
            mdi:gauge
          {% endif %}

##########################################################################################
# SCRIPTS
##########################################################################################

script:
  ############################################################################
  # SETPOINT SYNC (cloud → UI helper)
  ############################################################################
  master_bedroom_setpoint_sync_from_climate:
    alias: Master Bedroom Setpoint Sync From Climate
    mode: restart
    sequence:
      - variables:
          sp: "{{ state_attr('climate.master_bedroom', 'temperature') | float(0) }}"
      - service: input_number.set_value
        target:
          entity_id: input_number.master_bedroom_setpoint_ui
        data:
          value: "{{ sp }}"

  ############################################################################
  # SETPOINT ADJUST (Chevron buttons)
  ############################################################################
  master_bedroom_setpoint_adjust:
    alias: Master Bedroom Setpoint Adjust
    mode: queued
    fields:
      step:
        description: "Step in degrees C, e.g. -0.5 or 0.5"
        example: -0.5
    sequence:
      - condition: template
        value_template: >
          {% set s = states('climate.master_bedroom') | lower %}
          {{ s not in ['off','unavailable','unknown','none',''] }}

      - variables:
          cur_ui: "{{ states('input_number.master_bedroom_setpoint_ui') | float(0) }}"
          cur_cl: "{{ state_attr('climate.master_bedroom', 'temperature') | float(0) }}"
          cur: "{{ cur_ui if cur_ui > 0 else cur_cl }}"
          raw: "{{ cur + (step | float(0)) }}"
          new: "{{ [30, [10, raw] | max] | min | round(1) }}"

      - service: input_number.set_value
        target:
          entity_id: input_number.master_bedroom_setpoint_ui
        data:
          value: "{{ new }}"

      - service: climate.set_temperature
        target:
          entity_id: climate.master_bedroom
        data:
          temperature: "{{ new }}"

  ############################################################################
  # HVAC MODE SCRIPTS
  ############################################################################

  master_bedroom_hvac_off:
    alias: Master Bedroom HVAC - Off
    mode: restart
    sequence:
      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_hvac_requested_mode
        data:
          option: "off"

      - service: climate.turn_off
        target:
          entity_id: climate.master_bedroom

      - service: climate.set_preset_mode
        target:
          entity_id: climate.master_bedroom
        data:
          preset_mode: "none"

  master_bedroom_hvac_heat:
    alias: Master Bedroom HVAC - Heat
    mode: restart
    sequence:
      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_hvac_requested_mode
        data:
          option: "heat"

      - service: climate.turn_on
        target:
          entity_id: climate.master_bedroom

      - service: climate.set_hvac_mode
        target:
          entity_id: climate.master_bedroom
        data:
          hvac_mode: "heat"

  master_bedroom_hvac_cool:
    alias: Master Bedroom HVAC - Cool
    mode: restart
    sequence:
      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_hvac_requested_mode
        data:
          option: "cool"

      - service: climate.turn_on
        target:
          entity_id: climate.master_bedroom

      - service: climate.set_hvac_mode
        target:
          entity_id: climate.master_bedroom
        data:
          hvac_mode: "cool"

  master_bedroom_hvac_dry:
    alias: Master Bedroom HVAC - Dehumid
    mode: restart
    sequence:
      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_hvac_requested_mode
        data:
          option: "dry"

      - service: climate.turn_on
        target:
          entity_id: climate.master_bedroom

      - service: climate.set_hvac_mode
        target:
          entity_id: climate.master_bedroom
        data:
          hvac_mode: "dry"

  ############################################################################
  # PROFILE SCRIPTS
  ############################################################################

  master_bedroom_heat_pump_profile_apply:
    alias: Master Bedroom Heat Pump - Apply Profile
    mode: restart
    fields:
      profile:
        description: Profile name (Normal, Boost, Quiet)
    sequence:
      - variables:
          p: "{{ profile | default(states('input_select.master_bedroom_heat_pump_profile')) }}"
          preset_for_profile: >-
            {% if p == 'Normal' %}none
            {% elif p == 'Boost' %}boost
            {% elif p == 'Quiet' %}eco
            {% else %}none
            {% endif %}

      - service: climate.turn_on
        target:
          entity_id: climate.master_bedroom

      - service: climate.set_preset_mode
        target:
          entity_id: climate.master_bedroom
        data:
          preset_mode: "{{ preset_for_profile }}"

  master_bedroom_heat_pump_profile_next:
    alias: Master Bedroom Heat Pump - Next Profile
    mode: restart
    sequence:
      - variables:
          cur: "{{ states('input_select.master_bedroom_heat_pump_profile') }}"
          nxt: >-
            {% if cur == 'Normal' %}Boost
            {% elif cur == 'Boost' %}Quiet
            {% else %}Normal
            {% endif %}

      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_heat_pump_profile
        data:
          option: "{{ nxt }}"

      - service: script.turn_on
        target:
          entity_id: script.master_bedroom_heat_pump_profile_apply
        data:
          variables:
            profile: "{{ nxt }}"

##########################################################################################
# AUTOMATIONS
##########################################################################################

automation:
  ############################################################################
  # Sleep Timer Start / Cancel
  ############################################################################
  - alias: "Start or Cancel Master Bedroom Climate Timer"
    mode: restart
    trigger:
      - platform: state
        entity_id: input_select.master_bedroom_climate_timer_duration

    variables:
      opt: "{{ states('input_select.master_bedroom_climate_timer_duration') }}"
      dur_map:
        "1 hour": "01:00:00"
        "2 hours": "02:00:00"
        "3 hours": "03:00:00"
        "6 hours": "06:00:00"

    action:
      - choose:
          - conditions:
              - condition: template
                value_template: "{{ opt in dur_map }}"
            sequence:
              - service: timer.cancel
                target:
                  entity_id: timer.master_bedroom_climate_timer
              - delay: "00:00:01"
              - service: timer.start
                target:
                  entity_id: timer.master_bedroom_climate_timer
                data:
                  duration: "{{ dur_map[opt] }}"

          - conditions:
              - condition: state
                entity_id: input_select.master_bedroom_climate_timer_duration
                state: "Cancel timer"
            sequence:
              - service: timer.cancel
                target:
                  entity_id: timer.master_bedroom_climate_timer

  ############################################################################
  # Turn off heat pump when timer finishes
  ############################################################################
  - alias: "Turn Off Master Bedroom Climate on Timer Completion"
    trigger:
      - platform: event
        event_type: timer.finished
        event_data:
          entity_id: timer.master_bedroom_climate_timer
    action:
      - service: climate.turn_off
        target:
          entity_id: climate.master_bedroom
      - service: input_select.select_option
        target:
          entity_id: input_select.master_bedroom_climate_timer_duration
        data:
          option: "Cancel timer"

  ############################################################################
  # Sync setpoint from climate → UI helper
  ############################################################################
  - id: master_bedroom_setpoint_sync
    alias: Master Bedroom Setpoint Sync
    mode: restart
    trigger:
      - platform: state
        entity_id: climate.master_bedroom
      - platform: homeassistant
        event: start
    action:
      - service: script.master_bedroom_setpoint_sync_from_climate

  ############################################################################
  # Clear requested HVAC mode when cloud catches up
  ############################################################################
  - id: master_bedroom_hvac_clear_requested_mode
    alias: Master Bedroom HVAC - Clear Requested Mode
    mode: restart
    trigger:
      - platform: state
        entity_id: climate.master_bedroom
      - platform: state
        entity_id: input_select.master_bedroom_hvac_requested_mode
        to: ["off", "heat", "cool", "dry"]

    condition:
      - condition: template
        value_template: >
          {{ states('input_select.master_bedroom_hvac_requested_mode') != 'none' }}

    action:
      - delay: "00:00:03"

      - choose:
          - conditions:
              - condition: template
                value_template: >
                  {% set req = states('input_select.master_bedroom_hvac_requested_mode') %}
                  {% set mode = states('climate.master_bedroom') %}
                  {% set action = (state_attr('climate.master_bedroom','hvac_action') or '') %}
                  {{ (req == 'off' and (mode == 'off' or action == 'off'))
                    or (req in ['heat','cool','dry'] and mode == req) }}
            sequence:
              - service: input_select.select_option
                target:
                  entity_id: input_select.master_bedroom_hvac_requested_mode
                data:
                  option: "none"

        default:
          - delay: "00:00:25"
          - service: input_select.select_option
            target:
              entity_id: input_select.master_bedroom_hvac_requested_mode
            data:
              option: "none"

  ############################################################################
  # Sync Profile from actual preset_mode
  ############################################################################
  - id: master_bedroom_heat_pump_profile_sync_from_entities
    alias: Master Bedroom Heat Pump - Sync Profile From Entities
    mode: restart
    trigger:
      - platform: state
        entity_id: climate.master_bedroom
    action:
      - delay: "00:00:02"
      - variables:
          preset: "{{ state_attr('climate.master_bedroom', 'preset_mode') or 'none' }}"
          new_profile: >-
            {% if preset == 'boost' %}
              Boost
            {% elif preset == 'eco' %}
              Quiet
            {% else %}
              Normal
            {% endif %}
      - choose:
          - conditions:
              - condition: template
                value_template: "{{ states('input_select.master_bedroom_heat_pump_profile') != new_profile }}"
            sequence:
              - service: input_select.select_option
                target:
                  entity_id: input_select.master_bedroom_heat_pump_profile
                data:
                  option: "{{ new_profile }}"
