import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DuotecnoClient, DuotecnoConfigFlow, DuotecnoIntegration, DuotecnoMapper, HomeAssistantDuotecnoIntegration, createDuotecnoDiscoveryDescriptor, duotecnoProfile, type IDuotecnoSnapshot } from '../../ts/integrations/duotecno/index.js';

const rawData = {
  device: {
    id: 'duotecno-controller-1',
    name: 'Duotecno Controller',
    manufacturer: 'Duotecno',
  },
  entities: [
    { id: 'input_1', name: 'Input 1', platform: 'binary_sensor', state: true },
    { id: 'living_room_temperature', name: 'Living Room Temperature', platform: 'climate', state: 21.5, writable: true, attributes: { targetTemperature: 22 } },
    { id: 'shutter', name: 'Shutter', platform: 'cover', state: 'open', writable: true },
    { id: 'entry_light', name: 'Entry Light', platform: 'light', state: true, writable: true },
    { id: 'pump', name: 'Pump', platform: 'switch', state: false, writable: true },
  ],
};

tap.test('matches manual Duotecno candidates and creates config flow output', async () => {
  const descriptor = createDuotecnoDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'duotecno-manual-match');
  const result = await matcher!.matches({ host: 'duotecno.local', name: 'Duotecno Controller', metadata: { rawData } }, {});

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

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

  const done = await (await new DuotecnoConfigFlow().start(result.candidate!, {})).submit!({ password: 'secret', port: 1234 });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('duotecno.local');
});

tap.test('maps Duotecno raw snapshots to runtime devices and entities', async () => {
  const client = new DuotecnoClient({ name: 'Duotecno Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = DuotecnoMapper.toDevices(snapshot);
  const entities = DuotecnoMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('duotecno');
  expect(devices[0].manufacturer).toEqual('Duotecno');
  expect(entities.length).toEqual(5);
});

tap.test('exposes Duotecno runtime services without fake live control', async () => {
  const integration = new HomeAssistantDuotecnoIntegration();
  expect(integration.domain).toEqual('duotecno');
  expect(integration.status).toEqual('control-runtime');
  expect(duotecnoProfile.metadata.requirements).toEqual(['pyDuotecno==2024.10.1']);
  expect(duotecnoProfile.metadata.configFlow).toEqual(true);

  const runtime = await new DuotecnoIntegration().setup({ name: 'Duotecno Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'duotecno', service: 'status', target: {} });
  const snapshot = status.data as IDuotecnoSnapshot;

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

  const liveCommand = await runtime.callService!({ domain: 'cover', service: 'open_cover', target: {} });
  expect(liveCommand.success).toBeFalse();
  expect(Boolean(liveCommand.error)).toBeTrue();
  await runtime.destroy();

  const executorRuntime = await new DuotecnoIntegration().setup({
    name: 'Duotecno Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'light', service: 'turn_on', target: {}, data: { brightness: 128 } });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
