"""HA Full Inventory — run inside the HA container via docker cp + docker exec.

Usage:
    docker cp /tmp/ha_full_inventory.py homeassistant:/tmp/
    docker exec homeassistant python3 /tmp/ha_full_inventory.py

Lists all devices (with area, manufacturer, model, MAC), all integrations, and
all entities grouped by domain. No API token needed — reads .storage/ JSON directly.
"""

import json

with open('/config/.storage/core.area_registry') as f:
    areas = {a['id']: a['name'] for a in json.load(f)['data']['areas']}

with open('/config/.storage/core.device_registry') as f:
    devices = json.load(f)['data']['devices']

print('=== DEVICES ({}) ==='.format(len(devices)))
for d in devices:
    area = areas.get(d.get('area_id', ''), '-')
    mfr = d.get('manufacturer', '') or '-'
    model = d.get('model', '') or '-'
    name = d.get('name_by_user') or d.get('name', '?')
    disabled = d.get('disabled_by', '') or ''
    connections = d.get('connections', [])
    flag = '  [DISABLED]' if disabled else ''
    print('---')
    print('  Name: {} {}'.format(name, flag))
    print('  Area: {}'.format(area))
    print('  Manufacturer: {} | Model: {}'.format(mfr, model))
    for conn in connections:
        print('  {}: {}'.format(conn[0], conn[1]))

print()

with open('/config/.storage/core.config_entries') as f:
    entries = json.load(f)['data']['entries']

print('=== INTEGRATIONS ({}) ==='.format(len(entries)))
for e in entries:
    domain = e['domain']
    title = e.get('title', '?')
    disabled = e.get('disabled_by', '') or ''
    flag = '  [DISABLED]' if disabled else '  [ACTIVE]'
    print('  {} | {} {}'.format(domain, title, flag))

print()

with open('/config/.storage/core.entity_registry') as f:
    entities = json.load(f)['data']['entities']

print('=== ENTITIES ({}) grouped by domain ==='.format(len(entities)))
by_domain = {}
for e in entities:
    domain = e.get('domain', 'unknown')  # some older entities lack domain key
    if domain not in by_domain:
        by_domain[domain] = []
    by_domain[domain].append(e['entity_id'])

for domain, ids in sorted(by_domain.items()):
    print('  {} ({} entities):'.format(domain, len(ids)))
    for eid in sorted(ids):
        print('    - ' + eid)

print()
print('TOTAL: {} devices, {} integrations, {} entities'.format(
    len(devices), len(entries), len(entities)))
