import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FluxLedClient, FluxLedConfigFlow, FluxLedIntegration, FluxLedMapper, HomeAssistantFluxLedIntegration, createFluxLedDiscoveryDescriptor, fluxLedProfile, type IFluxLedSnapshot, type TFluxLedRawData } from '../../ts/integrations/flux_led/index.js';

const rawData: TFluxLedRawData = {
  ipaddr: '192.0.2.20',
  id: 'accf23010203',
  model: 'RGBW',
  model_description: 'Magic Home RGBW',
  model_num: 35,
  version_num: 10,
  is_on: true,
  brightness: 128,
  color_mode: 'rgbw',
  rgb: [255, 32, 16],
  effect: 'rainbow',
  effect_list: ['rainbow', 'jump'],
  speed: 47,
  paired_remotes: 2,
  operating_modes: ['rgb', 'rgbw'],
  operating_mode: 'rgbw',
  remote_access_host: 'remote.example',
  remote_access_enabled: false,
};

tap.test('matches manual Magic Home candidates and creates config flow output', async () => {
  const descriptor = createFluxLedDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'flux_led-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: '192.0.2.20', name: 'Magic Home RGBW 010203', metadata: { rawData } }, {});

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

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

  const done = await (await new FluxLedConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.20');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Magic Home raw snapshots to devices and entities', async () => {
  const client = new FluxLedClient({ rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = FluxLedMapper.toSnapshotFromRaw({}, rawData);
  const devices = FluxLedMapper.toDevices(mappedSnapshot);
  const entities = FluxLedMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('flux_led');
  expect(devices[0].manufacturer).toEqual('Zengge');
  expect(entities.some((entityArg) => entityArg.platform === 'light' && entityArg.state === true)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'number.magic_home_rgbw_010203_effect_speed')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'button.magic_home_rgbw_010203_restart')).toBeTrue();
});

tap.test('exposes Magic Home read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FluxLedIntegration();
  const alias = new HomeAssistantFluxLedIntegration();
  expect(alias instanceof FluxLedIntegration).toBeTrue();
  expect(alias.domain).toEqual('flux_led');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fluxLedProfile.metadata.configFlow).toEqual(true);
  expect(Object.prototype.hasOwnProperty.call(fluxLedProfile.metadata, 'qualityScale')).toBeTrue();
  expect(fluxLedProfile.metadata.qualityScale).toBeUndefined();
  expect(fluxLedProfile.metadata.dependencies).toEqual(['network']);
  expect(fluxLedProfile.metadata.requirements).toEqual(['flux-led==1.2.0']);

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

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.entities.some((entityArg) => entityArg.id === 'light')).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Magic Home RGBW 010203');

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

export default tap.start();
