import { expect, tap } from '@git.zone/tstest/tapbundle';
import { CpuspeedClient, CpuspeedConfigFlow, CpuspeedIntegration, CpuspeedMapper, HomeAssistantCpuspeedIntegration, cpuspeedProfile, createCpuspeedDiscoveryDescriptor, type ICpuspeedSnapshot } from '../../ts/integrations/cpuspeed/index.js';

const rawData = {
  actual_ghz: 3.18,
  advertised_ghz: 3.4,
  arch: 'x86_64',
  brand: 'Example CPU',
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('cpuspeed');
  expect(devices[0].name).toEqual('CPU Speed Test');
  expect(entities.length > 0).toBeTrue();
});

tap.test('exposes CPU Speed read-only runtime without control services', async () => {
  expect(new HomeAssistantCpuspeedIntegration().domain).toEqual('cpuspeed');
  expect(cpuspeedProfile.status).toEqual('read-only-runtime');
  expect(cpuspeedProfile.metadata.configFlow).toBeTrue();
  expect(cpuspeedProfile.metadata.requirements).toEqual(['py-cpuinfo==9.0.0']);
  expect(Object.prototype.hasOwnProperty.call(cpuspeedProfile.metadata, 'qualityScale')).toBeTrue();
  expect(cpuspeedProfile.metadata.qualityScale).toBeUndefined();

  const runtime = await new CpuspeedIntegration().setup({ name: 'CPU Speed Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'cpuspeed', service: 'status', target: {} });
  const snapshot = status.data as ICpuspeedSnapshot;

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

  const controlCommand = await runtime.callService!({ domain: 'cpuspeed', service: 'turn_on', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(Boolean(controlCommand.error?.includes('requires an injected'))).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
