import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EmonitorClient, EmonitorConfigFlow, EmonitorIntegration, EmonitorMapper, HomeAssistantEmonitorIntegration, createEmonitorDiscoveryDescriptor, emonitorProfile, type IEmonitorSnapshot } from '../../ts/integrations/emonitor/index.js';

const rawData = {
  network: {
    mac_address: '00:90:C2:12:34:56',
  },
  hardware: {
    firmware_version: '1.2.3',
    serial_number: 'EMON123456',
  },
  channels: {
    1: { active: true, label: 'Mains', inst_power: 100, avg_power: 90, max_power: 130, paired_with_channel: 2 },
    2: { active: true, label: 'Mains B', inst_power: 50, avg_power: 45, max_power: 70, paired_with_channel: 1 },
    3: { active: false, label: 'Spare', inst_power: 0, avg_power: 0, max_power: 0 },
    4: { active: true, label: 'Solar', inst_power: 321, avg_power: 300, max_power: 350 },
  },
};

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

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

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

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

tap.test('maps Emonitor raw status snapshots to power devices and entities', async () => {
  const client = new EmonitorClient({ host: 'emonitor.local', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EmonitorMapper.toDevices(snapshot);
  const entities = EmonitorMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('emonitor');
  expect(devices[0].manufacturer).toEqual('Powerhouse Dynamics, Inc.');
  expect(devices[0].name).toEqual('Emonitor 123456');
  expect(entities.length).toEqual(6);
  expect(entities[0].state).toEqual(150);
  expect(entities[0].attributes?.unit).toEqual('W');
  expect(entities[0].attributes?.deviceClass).toEqual('power');
});

tap.test('exposes Emonitor read-only runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new EmonitorIntegration();
  const alias = new HomeAssistantEmonitorIntegration();
  expect(alias.domain).toEqual('emonitor');
  expect(integration.status).toEqual('read-only-runtime');
  expect(emonitorProfile.metadata.configFlow).toEqual(true);
  expect(emonitorProfile.metadata.requirements).toEqual(['aioemonitor==1.0.5']);

  const runtime = await integration.setup({ rawData }, {});
  const status = await runtime.callService!({ domain: 'emonitor', service: 'status', target: {} });
  const snapshot = status.data as IEmonitorSnapshot;

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

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

export default tap.start();
