import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHomeworksIntegration, HomeworksClient, HomeworksConfigFlow, HomeworksIntegration, HomeworksMapper, createHomeworksDiscoveryDescriptor, homeworksProfile, type IHomeworksSnapshot, type THomeworksRawData } from '../../ts/integrations/homeworks/index.js';

const rawData: THomeworksRawData = {
  device: {
    id: 'homeworks-main',
    name: 'Lutron Homeworks',
    manufacturer: 'Lutron',
    model: 'Homeworks controller',
    host: 'homeworks.local',
  },
  entities: [
    { id: 'kitchen_dimmer', name: 'Kitchen Dimmer', platform: 'light', state: 128, writable: true, attributes: { address: '[02:08:02:01]', rate: 1 } },
    { id: 'keypad_button_1', name: 'Keypad Button 1', platform: 'button', state: 'idle', writable: true, attributes: { address: '[02:08:02:02]', number: 1 } },
    { id: 'keypad_led_1', name: 'Keypad LED 1', platform: 'binary_sensor', state: true, attributes: { address: '[02:08:02:02]', number: 1 } },
  ],
  controllerId: 'lutron_homeworks',
};

tap.test('matches manual Homeworks candidates and creates config flow output', async () => {
  const descriptor = createHomeworksDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homeworks-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'lutron_homeworks', name: 'Lutron Homeworks', host: 'homeworks.local', metadata: { rawData } }, {});

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

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

  const done = await (await new HomeworksConfigFlow().start(result.candidate!, {})).submit!({ port: 23 });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('homeworks.local');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Homeworks raw snapshots to runtime devices and entities', async () => {
  const client = new HomeworksClient({ name: 'Homeworks Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = HomeworksMapper.toSnapshotFromRaw({ name: 'Homeworks Runtime' }, rawData);
  const devices = HomeworksMapper.toDevices(mappedSnapshot);
  const entities = HomeworksMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('homeworks');
  expect(devices[0].manufacturer).toEqual('Lutron');
  expect(entities.some((entityArg) => entityArg.id === 'light.lutron_homeworks_kitchen_dimmer')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'button.lutron_homeworks_keypad_button_1')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.lutron_homeworks_keypad_led_1')).toBeTrue();
});

tap.test('exposes Homeworks read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HomeworksIntegration();
  const alias = new HomeAssistantHomeworksIntegration();
  expect(alias instanceof HomeworksIntegration).toBeTrue();
  expect(alias.domain).toEqual('homeworks');
  expect(integration.status).toEqual('read-only-runtime');
  expect(homeworksProfile.metadata.configFlow).toEqual(true);
  expect(homeworksProfile.metadata.requirements).toEqual(['pyhomeworks==1.1.2']);
  expect(homeworksProfile.metadata.dependencies).toEqual([]);

  const runtime = await integration.setup({ name: 'Homeworks Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'homeworks', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'homeworks', service: 'refresh', target: {} });
  const snapshot = status.data as IHomeworksSnapshot;

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

  const command = await runtime.callService!({ domain: 'homeworks', service: 'send_command', target: {}, data: { controller_id: 'lutron_homeworks', command: ['KBP, [02:08:02:02], 1'] } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
