#!/usr/bin/env python3
import json
import urllib.request

TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhNTk3MGM3YTQxNTE0YjZhYjg1OTNjZjJjMWY2NGQ0MyIsImlhdCI6MTc2NzI1OTE1MCwiZXhwIjoyMDgyNjE5MTUwfQ.hjng9QODqQsGLly3OXCKp7f5CPM6XcpgRLztVnPynTU"
HA_URL = "http://localhost:8123"

# Read entity registry
with open('/config/.storage/core.entity_registry', 'r') as f:
    registry = json.load(f)

# Find entities exposed to conversation
exposed = []
for entity in registry['data']['entities']:
    if entity.get('options', {}).get('conversation', {}).get('should_expose'):
        exposed.append(entity['entity_id'])

# Expose each to Alexa
for entity_id in exposed:
    data = json.dumps({
        "entity_id": entity_id,
        "assistants": ["alexa"]
    }).encode('utf-8')
    
    req = urllib.request.Request(
        f"{HA_URL}/api/services/homeassistant/expose_entity",
        data=data,
        headers={
            'Authorization': f'Bearer {TOKEN}',
            'Content-Type': 'application/json'
        },
        method='POST'
    )
    
    try:
        urllib.request.urlopen(req, timeout=5)
        print(f"Exposed: {entity_id}")
    except Exception as e:
        print(f"Failed: {entity_id} - {e}")

print(f"Synced {len(exposed)} entities")
