import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHueBleIntegration, HueBleClient, HueBleConfigFlow, HueBleIntegration, HueBleMapper, createHueBleDiscoveryDescriptor, hueBleProfile, type IHueBleSnapshot, type THueBleRawData } from '../../ts/integrations/hue_ble/index.js';

const rawData: THueBleRawData = {
  device: {
    id: 'aa:bb:cc:dd:ee:ff',
    name: 'Hue BLE Lamp',
    manufacturer: 'Philips Hue',
    model: 'Hue BLE light',
    serialNumber: 'AA:BB:CC:DD:EE:FF',
    protocol: 'local',
  },
  entities: [
    {
      id: 'light',
      name: 'Light',
      platform: 'light',
      state: true,
      writable: true,
      attributes: {
        brightness: 190,
        colorMode: 'color_temp',
        colorTempKelvin: 2700,
        supportedColorModes: ['brightness', 'color_temp', 'xy'],
        xyColor: [0.45, 0.41],
      },
    },
  ],
};

tap.test('matches manual Hue BLE candidates and creates config flow output', async () => {
  const descriptor = createHueBleDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'hue_ble-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'aa:bb:cc:dd:ee:ff', name: 'Hue BLE Lamp', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('hue_ble');

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new HueBleConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Hue BLE Lamp');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Hue BLE raw snapshots to runtime devices and entities', async () => {
  const client = new HueBleClient({ rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = HueBleMapper.toSnapshotFromRaw({}, rawData);
  const devices = HueBleMapper.toDevices(mappedSnapshot);
  const entities = HueBleMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('hue_ble');
  expect(devices[0].manufacturer).toEqual('Philips Hue');
  expect(entities.some((entityArg) => entityArg.id === 'light.hue_ble_lamp_light')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'light.hue_ble_lamp_light')?.attributes?.brightness).toEqual(190);
});

tap.test('exposes Hue BLE read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HueBleIntegration();
  const alias = new HomeAssistantHueBleIntegration();
  expect(alias instanceof HueBleIntegration).toBeTrue();
  expect(alias.domain).toEqual('hue_ble');
  expect(integration.status).toEqual('read-only-runtime');
  expect(hueBleProfile.metadata.configFlow).toEqual(true);
  expect(hueBleProfile.metadata.qualityScale).toEqual('bronze');
  expect(hueBleProfile.metadata.dependencies).toEqual(['bluetooth_adapters']);

  const runtime = await integration.setup({ rawData }, {});
  const status = await runtime.callService!({ domain: 'light', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'hue_ble', service: 'refresh', target: {} });
  const snapshot = status.data as IHueBleSnapshot;

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Hue BLE Lamp');

  const command = await runtime.callService!({ domain: 'light', service: 'turn_on', target: { entityId: 'light.hue_ble_lamp_light' }, data: { brightness: 255 } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
