#:########################################################################################:#
# Main Sony TV Automations Package                                                       #
#:########################################################################################:#
#
# TITLE:
#   Main Sony TV Automations
#
# FILE:
#   packages/main_sony_tv_automations.yaml
#
# VERSION:
#   V1.1 2026-07-20
#
# VERSION HISTORY:
#   V1.1 2026-07-20
#     - Added structured documentation and automation descriptions.
#
#   V1.0
#     - Initial MQTT TV-off and surround-amplifier following automations.
#
# PURPOSE:
#   Accepts an MQTT command to turn off the lounge TV and keeps the loft
#   surround-amplifier power synchronized with the TV remote state.
#
# MQTT COMMAND:
#   Topic:
#     viewroad-commands/maintv/action
#
#   Payload:
#     OFF
#
#   The payload is uppercase and this package does not provide an MQTT ON action.
#
# AMPLIFIER FOLLOWING:
#   - remote.lounge_tv is the source-of-truth state for the amplifier.
#   - The remote state must remain on or off for five seconds before action.
#   - Restart mode cancels the previous wait when another state change occurs,
#     preventing brief transitions from toggling amplifier power.
#
# DEPENDENCIES:
#   - remote.lounge_tv controls and reports the Sony lounge TV state.
#   - switch.tv_surround_amp_power_in_loft_x27pp controls amplifier power.
#
#:########################################################################################:#

automation:
  - id: "1669966515993"
    alias: Turn off Lounge TV
    description: "Turns off the lounge TV when the MQTT OFF command is received."
    trigger:
      - platform: mqtt
        topic: viewroad-commands/maintv/action
        payload: "OFF"
    condition: []
    action:
      - type: turn_off
        device_id: 4a9f71fc64e158f1c9286d6e43ce782e
        entity_id: remote.lounge_tv
        domain: remote
    mode: single

  - id: tv_amp_follow_remote_state
    alias: Lounge surround amp follows TV remote (5s debounce)
    description: "Follows the stable lounge TV remote state after a five-second debounce."
    mode: restart
    trigger:
      - platform: state
        entity_id: remote.lounge_tv
        to: "on"
        for: "00:00:05"
      - platform: state
        entity_id: remote.lounge_tv
        to: "off"
        for: "00:00:05"
    action:
      - choose:
          - conditions:
              - condition: state
                entity_id: remote.lounge_tv
                state: "on"
            sequence:
              - service: switch.turn_on
                target:
                  entity_id: switch.tv_surround_amp_power_in_loft_x27pp
        default:
          - service: switch.turn_off
            target:
              entity_id: switch.tv_surround_amp_power_in_loft_x27pp
