import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ArwnClient, ArwnConfigFlow, ArwnIntegration, ArwnMapper, createArwnDiscoveryDescriptor, type IArwnSnapshot } from '../../ts/integrations/arwn/index.js';

const rawData = {
  "temperature": 21.8,
  "humidity": 44,
  "raining": false
};

tap.test('matches manual ARWN candidates and creates config flow output', async () => {
  const descriptor = createArwnDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'arwn-manual-match');
  const result = await matcher!.matches({ host: 'arwn.local', name: 'Ambient Radio Weather Network', metadata: { rawData } }, {});

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

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

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

tap.test('maps ARWN raw snapshots to runtime devices and entities', async () => {
  const snapshot = ArwnMapper.toSnapshotFromRaw({ name: 'ARWN Test' }, rawData);
  const clientSnapshot = await new ArwnClient({ name: 'ARWN Test', rawData }).getSnapshot();
  const devices = ArwnMapper.toDevices(clientSnapshot);
  const entities = ArwnMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('arwn');
  expect(entities.find((entityArg) => entityArg.name === 'Temperature')?.state).toEqual(21.8);
  expect(entities.find((entityArg) => entityArg.name === 'Raining')?.platform).toEqual('binary_sensor');
});

tap.test('exposes ARWN runtime status without fake live control', async () => {
  const runtime = await new ArwnIntegration().setup({ name: 'ARWN Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'arwn', service: 'status', target: {} });
  const snapshot = status.data as IArwnSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('ARWN Runtime');

  const liveCommand = await runtime.callService!({ domain: 'arwn', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
