#!/bin/bash
# Turn Midea AC ON with temp 21 + ECO mode
ENTITY="climate.152832117784908_climate"

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)

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

# 2. Temperatur 21°C
curl -s -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"entity_id\": \"$ENTITY\", \"temperature\": 21}" \
  "http://localhost:8123/api/services/climate/set_temperature"

# 3. ECO-Modus
curl -s -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"entity_id\": \"$ENTITY\", \"preset_mode\": \"eco\"}" \
  "http://localhost:8123/api/services/climate/set_preset_mode"

echo "AC ON (cool, 21°C, ECO) at $(date)"
