# Home Assistant Configuration for BTB RSS Reader Integration
# Add this to your configuration.yaml or automations.yaml

automation:
  - alias: "BTB Podcast Play via Webhook"
    description: "Play Behind the Bastards episodes from RSS reader (supports Nabu Casa cloud)"
    trigger:
      - platform: webhook
        webhook_id: btb_play_episode
        allowed_methods:
          - POST
        local_only: false  # MUST be false for Nabu Casa cloud webhooks to work
    action:
      - service: media_player.play_media
        target:
          entity_id: "{{ trigger.json.media_player | default('media_player.family_room_speaker') }}"
        data:
          media_content_id: "{{ trigger.json.episode_url }}"
          media_content_type: "music"
          extra:
            title: "{{ trigger.json.episode_title }}"
            artist: "Behind the Bastards"
            album: "BTB Episodes"
      - service: persistent_notification.create
        data:
          title: "🎧 Now Playing BTB"
          message: "{{ trigger.json.episode_title }}\nPublished: {{ trigger.json.pub_date }}\nDuration: {{ trigger.json.duration }}"
          notification_id: "btb_playing"
      - service: logbook.log
        data:
          name: "BTB RSS Reader"
          message: "Started playing: {{ trigger.json.episode_title }}"
          entity_id: "{{ trigger.json.media_player | default('media_player.family_room_speaker') }}"

# Optional: Create input selects for media player choice
input_select:
  btb_media_player:
    name: "BTB Default Media Player"
    options:
      - media_player.family_room_speaker
      - media_player.bedroom_speaker
      - media_player.kitchen_display
      - media_player.office_computer
    initial: media_player.family_room_speaker
    icon: mdi:speaker

# Optional: Script for more advanced playback control
script:
  play_btb_episode:
    alias: "Play BTB Episode"
    description: "Play Behind the Bastards episode with queue management"
    fields:
      episode_url:
        description: "Direct URL to episode audio file"
        example: "https://example.com/episode.opus"
      episode_title:
        description: "Episode title"
        example: "Part One: The Bastard of the Week"
      media_player:
        description: "Target media player entity"
        example: "media_player.family_room_speaker"
      duration:
        description: "Episode duration"
        example: "1:23:45"
      pub_date:
        description: "Publication date"
        example: "2024-09-19"
    sequence:
      - service: media_player.clear_playlist
        target:
          entity_id: "{{ media_player | default(states('input_select.btb_media_player')) }}"
      - service: media_player.play_media
        target:
          entity_id: "{{ media_player | default(states('input_select.btb_media_player')) }}"
        data:
          media_content_id: "{{ episode_url }}"
          media_content_type: "music"
          extra:
            title: "{{ episode_title }}"
            artist: "Behind the Bastards"
            album: "BTB Episodes"
            duration: "{{ duration }}"
      - service: persistent_notification.create
        data:
          title: "🎧 BTB Now Playing"
          message: |
            **{{ episode_title }}**
            📅 {{ pub_date }}
            ⏱️ {{ duration }}
            🔊 {{ media_player | default(states('input_select.btb_media_player')) }}
          notification_id: "btb_current_episode"

# Optional: Add rate limiting to prevent abuse
# Uncomment the condition section in the automation above:
#
# condition:
#   - condition: template
#     value_template: >
#       {{ (now() - states.automation.btb_podcast_play_via_webhook.attributes.last_triggered).total_seconds() > 10 }}

# Optional: Add secret token validation for additional security
# Uncomment the condition section in the automation above:
#
# condition:
#   - condition: template
#     value_template: >
#       {{ trigger.json.get('secret_token') == 'YOUR_RANDOM_SECRET_HERE' }}
#
# Then update the JavaScript payload in btb-rss.html to include secret_token

# ============================================================================
# NABU CASA CLOUD SETUP
# ============================================================================
# 
# To get your Nabu Casa webhook URL:
# 1. Go to Settings → Home Assistant Cloud
# 2. Click "Webhooks" tab
# 3. Find or create webhook ID: btb_play_episode
# 4. Copy the full webhook URL (format: https://hooks.nabu.casa/gAAAAAB...)
# 5. Enter this URL in the RSS reader's ⚙️ HA Setup dialog
#
# Note: CORS is handled by the PHP proxy, NOT by Home Assistant configuration.
# You do NOT need to modify http: configuration in HA for CORS.

# ============================================================================
# LOCAL NETWORK SETUP (Alternative to Nabu Casa)
# ============================================================================
#
# Webhook URL format: http://homeassistant.lan:8123/api/webhook/btb_play_episode
# 
# Change automation trigger to:
#   local_only: true  # Only accept requests from local network
#
# Limitations:
# - Only works when browser is on same network as Home Assistant
# - Cannot access from external networks/mobile data
# - More secure but less convenient

# ============================================================================
# SECURITY NOTES
# ============================================================================
#
# Current security model:
# - Webhook URL acts as bearer token (possession = access)
# - Nabu Casa URLs are cryptographically random (unguessable)
# - Risk limited to triggering podcast playback
# - No access to HA dashboard or other devices
#
# For this use case (playing podcasts), security-by-obscurity is acceptable.
# If you need stronger security, implement rate limiting or secret token validation.