#!/bin/bash
# Midea AC control via Home Assistant API — reusable cronjob script
# Usage: ha-ac-cronjob.sh <hvac_mode>
#   hvac_mode: off | cool | heat | dry | fan_only | auto
#
# Fetches a fresh access token before each call (tokens expire after 30 min).
# Designed for Hermes one-shot cronjobs (no_agent=true).

set -e

MODE="${1:-off}"
ENTITY="climate.152832117784908_climate"

# Validate mode
case "$MODE" in
  off|cool|heat|dry|fan_only|auto) ;;
  *) echo "ERROR: Invalid hvac_mode '$MODE'. Valid: off, cool, heat, dry, fan_only, auto"; exit 1 ;;
esac

# Get fresh access token via refresh-token exchange
TOKEN=$(docker exec homeassistant python3 -c "
import json, urllib.request, urllib.parse
with open('/config/.storage/auth') as f:
    auth = json.load(f)
for rt in auth['data']['refresh_tokens']:
    if rt['token_type'] == 'normal' and rt.get('last_used_at'):
        cid = rt.get('client_id', 'http://localhost:8123/')
        data = urllib.parse.urlencode({
            'grant_type': 'refresh_token',
            'refresh_token': rt['token'],
            'client_id': cid,
        }).encode()
        req = urllib.request.Request('http://localhost:8123/auth/token', data=data,
            headers={'Content-Type': 'application/x-www-form-urlencoded'})
        with urllib.request.urlopen(req) as resp:
            print(json.loads(resp.read())['access_token'])
        break
" 2>/dev/null)

if [ -z "$TOKEN" ]; then
  echo "ERROR: Failed to obtain access token"
  exit 1
fi

# Execute
RESPONSE=$(curl -s -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"entity_id\": \"$ENTITY\", \"hvac_mode\": \"$MODE\"}" \
  "http://localhost:8123/api/services/climate/set_hvac_mode")

echo "AC set to '$MODE' at $(date '+%Y-%m-%d %H:%M:%S %Z') — API response: $RESPONSE"
