import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EmoncmsHistoryClient, EmoncmsHistoryConfigFlow, EmoncmsHistoryIntegration, EmoncmsHistoryMapper, HomeAssistantEmoncmsHistoryIntegration, createEmoncmsHistoryDiscoveryDescriptor, emoncmsHistoryProfile, type IEmoncmsHistorySnapshot } from '../../ts/integrations/emoncms_history/index.js';

const rawData = {
  url: 'http://emoncms.local',
  inputnode: 12,
  payload: {
    'sensor.grid_power': 421.2,
    'sensor.solar_energy': 18.4,
  },
  units: {
    'sensor.grid_power': 'W',
    'sensor.solar_energy': 'kWh',
  },
};

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

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

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

  const done = await (await new EmoncmsHistoryConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('emoncms.local');
  expect(done.config?.path).toEqual('/input/post.json');
});

tap.test('maps Emoncms History raw payload snapshots to runtime devices and entities', async () => {
  const client = new EmoncmsHistoryClient({ name: 'History Exporter', rawData, whitelist: ['sensor.grid_power'] });
  const snapshot = await client.getSnapshot();
  const devices = EmoncmsHistoryMapper.toDevices(snapshot);
  const entities = EmoncmsHistoryMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('emoncms_history');
  expect(devices[0].manufacturer).toEqual('OpenEnergyMonitor');
  expect(entities.length).toEqual(2);
  expect(entities[0].state).toEqual(421.2);
  expect(entities[0].attributes?.unit).toEqual('W');
});

tap.test('exposes Emoncms History runtime services, HA alias, and executor-gated control', async () => {
  const integration = new EmoncmsHistoryIntegration();
  const alias = new HomeAssistantEmoncmsHistoryIntegration();
  expect(alias.domain).toEqual('emoncms_history');
  expect(integration.status).toEqual('control-runtime');
  expect(emoncmsHistoryProfile.metadata.configFlow).toEqual(false);
  expect(emoncmsHistoryProfile.metadata.requirements).toEqual(['pyemoncms==0.1.3']);

  const runtime = await integration.setup({ name: 'History Exporter', rawData }, {});
  const status = await runtime.callService!({ domain: 'emoncms_history', service: 'status', target: {} });
  const snapshot = status.data as IEmoncmsHistorySnapshot;

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

  const command = await runtime.callService!({ domain: 'emoncms_history', service: 'input_post', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
