import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIgloIntegration, IgloClient, IgloConfigFlow, IgloIntegration, IgloMapper, createIgloDiscoveryDescriptor, igloDefaultPort, igloProfile, type IIgloSnapshot, type TIgloRawData } from '../../ts/integrations/iglo/index.js';

const rawData: TIgloRawData = {
  device: {
    id: 'iglo-kitchen',
    name: 'Kitchen iGlo',
    manufacturer: 'iGlo',
    model: 'iGlo Light',
    host: '192.0.2.21',
    port: igloDefaultPort,
    attributes: {
      lightId: 0,
    },
  },
  entities: [
    { id: 'light', name: 'Light', platform: 'light', state: true, writable: true, attributes: { brightness: 153, brightnessScale: 255, colorMode: 'hs', hsColor: [32, 76], colorTempKelvin: 3200, effect: 'Rainbow', effectList: ['Rainbow', 'Pulse'] } },
  ],
};

tap.test('matches manual iGlo candidates and creates config flow output', async () => {
  const descriptor = createIgloDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'iglo-manual-match');
  const result = await matcher!.matches({ id: 'iglo-kitchen', host: '192.0.2.21', port: igloDefaultPort, name: 'Kitchen iGlo', metadata: { rawData } }, {});

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

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

  const done = await (await new IgloConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.21');
  expect(done.config?.port).toEqual(igloDefaultPort);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('iglo');
  expect(devices[0].manufacturer).toEqual('iGlo');
  expect(entities.some((entityArg) => entityArg.id === 'light.kitchen_iglo_light')).toBeTrue();
  expect(entities[0].attributes?.effect).toEqual('Rainbow');
});

tap.test('exposes iGlo read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IgloIntegration();
  const alias = new HomeAssistantIgloIntegration();
  expect(alias instanceof IgloIntegration).toBeTrue();
  expect(alias.domain).toEqual('iglo');
  expect(integration.status).toEqual('read-only-runtime');
  expect(igloProfile.metadata.configFlow).toEqual(false);
  expect(igloProfile.metadata.qualityScale).toEqual('legacy');
  expect(igloProfile.metadata.requirements).toEqual(['iglo==1.2.7']);

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

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

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

export default tap.start();
