import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EbusdClient, EbusdConfigFlow, EbusdIntegration, EbusdMapper, HomeAssistantEbusdIntegration, ebusdProfile, createEbusdDiscoveryDescriptor, type IEbusdSnapshot } from '../../ts/integrations/ebusd/index.js';

const rawData = {
  device: {
    id: 'ebusd-daemon-1',
    name: 'ebusd Boiler',
    manufacturer: 'ebusd',
    model: 'eBUS daemon',
    host: '192.0.2.30',
    port: 8888,
  },
  entities: [
    { id: 'Hc1FlowTemp', name: 'Hc1FlowTemp', platform: 'sensor', state: 41.5, unit: '°C', deviceClass: 'temperature' },
    { id: 'HwcOpMode', name: 'HwcOpMode', platform: 'sensor', state: 'auto' },
  ],
};

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

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('ebusd');
  expect(result.candidate?.port).toEqual(8888);

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

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

tap.test('maps ebusd raw snapshots to runtime devices and entities', async () => {
  const snapshot = EbusdMapper.toSnapshotFromRaw({ name: 'ebusd Test', rawData }, rawData);
  const devices = EbusdMapper.toDevices(snapshot);
  const entities = EbusdMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('ebusd');
  expect(devices[0].manufacturer).toEqual('ebusd');
  expect(entities.length).toEqual(2);
  expect(entities.some((entityArg) => entityArg.attributes?.deviceClass === 'temperature')).toBeTrue();
});

tap.test('exposes ebusd runtime services and executor-only writes', async () => {
  expect(new HomeAssistantEbusdIntegration().domain).toEqual('ebusd');
  expect(ebusdProfile.status).toEqual('control-runtime');
  expect(ebusdProfile.metadata.configFlow).toBeFalse();
  expect(ebusdProfile.metadata.requirements).toEqual(['ebusdpy==0.0.17']);

  const client = new EbusdClient({ name: 'ebusd Client', rawData });
  expect((await client.getSnapshot()).source).toEqual('manual');

  const runtime = await new EbusdIntegration().setup({ name: 'ebusd Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'ebusd', service: 'status', target: {} });
  const snapshot = status.data as IEbusdSnapshot;

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

  const writeCommand = await runtime.callService!({ domain: 'ebusd', service: 'write', target: {}, data: { name: 'Hc1MaxFlowTempDesired', value: 21 } });
  expect(writeCommand.success).toBeFalse();
  expect(writeCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
