"""
Collect Home Assistant sensor data and write to a Python file.
Don't call this script directly, use:
    .../ha-services/dev-cli.py update-ha-data
"""

import argparse
import datetime
import os
from pathlib import Path
from pprint import pp


def main(out):
    out.write('#\n')
    out.write("# DON'T CHANGE THIS FILE MANUALLY\n")
    out.write('#\n')
    out.write('# This file is generated by:\n')
    out.write('# .../ha-services/dev-cli.py update-ha-data\n')
    out.write('#\n')
    out.write(f'# Last Update: {datetime.datetime.now().isoformat()}\n')
    out.write('#\n')
    import homeassistant

    print(f'{homeassistant.__file__=}')

    from homeassistant.const import __version__

    out.write('# Generated with data from Home Assistant package:\n')
    out.write('#\n')
    out.write(f'# homeassistant v{__version__}\n')
    out.write('#\n')
    out.write('\n')

    from homeassistant.components.sensor import DEVICE_CLASS_STATE_CLASSES, DEVICE_CLASS_UNITS

    ha_sensor_data = []
    for device_class, units in DEVICE_CLASS_UNITS.items():
        state_classes = DEVICE_CLASS_STATE_CLASSES[device_class]
        ha_sensor_data.append(
            {
                'device_class': str(device_class),
                'state_classes': set(str(sc) for sc in state_classes),
                'units': set(str(unit) for unit in units if unit),
            }
        )

    out.write(f'HA_SENSOR_DATA = {ha_sensor_data!r}\n')
    pp(ha_sensor_data, width=os.get_terminal_size().columns)
    print(f'\n\nWrote data to: {out.name}')


if __name__ == '__main__':
    print('_' * 100)
    print(__file__)

    parser = argparse.ArgumentParser(description='Collect Home Assistant sensor data.')
    parser.add_argument('--output', type=str, help='Output file path', default='ha_sensor_data.py')
    args = parser.parse_args()

    output_path = Path(args.output)

    with output_path.open('w') as out:
        main(out)
