import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIammeterIntegration, IammeterClient, IammeterConfigFlow, IammeterIntegration, IammeterMapper, createIammeterDiscoveryDescriptor, iammeterProfile, type IIammeterSnapshot, type TIammeterRawData } from '../../ts/integrations/iammeter/index.js';

const rawData: TIammeterRawData = {
  device: {
    id: 'iammeter-12345678',
    name: 'IamMeter WEM3080T',
    manufacturer: 'IamMeter',
    model: 'WEM3080T',
    serialNumber: '12345678',
    host: '192.0.2.15',
    port: 80,
  },
  entities: [
    { id: 'Voltage_A', name: 'Voltage A', platform: 'sensor', state: 231.2, unit: 'V', deviceClass: 'voltage', stateClass: 'measurement' },
    { id: 'Current_A', name: 'Current A', platform: 'sensor', state: 4.1, unit: 'A', deviceClass: 'current', stateClass: 'measurement' },
    { id: 'Power_A', name: 'Power A', platform: 'sensor', state: 840, unit: 'W', deviceClass: 'power', stateClass: 'measurement' },
    { id: 'ImportEnergy_A', name: 'ImportEnergy A', platform: 'sensor', state: 1234.56, unit: 'kWh', deviceClass: 'energy', stateClass: 'total_increasing' },
  ],
  Model: 'WEM3080T',
  sn: '12345678',
};

tap.test('matches manual IamMeter candidates and creates config flow output', async () => {
  const descriptor = createIammeterDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'iammeter-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'iammeter-12345678', name: 'IamMeter WEM3080T', metadata: { rawData } }, {});

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

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

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

tap.test('maps IamMeter raw snapshots to runtime devices and entities', async () => {
  const client = new IammeterClient({ rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = IammeterMapper.toSnapshotFromRaw({}, rawData);
  const devices = IammeterMapper.toDevices(mappedSnapshot);
  const entities = IammeterMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('iammeter');
  expect(devices[0].manufacturer).toEqual('IamMeter');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.iammeter_wem3080t_voltage_a')).toBeTrue();
  expect(entities.find((entityArg) => entityArg.id === 'sensor.iammeter_wem3080t_power_a')?.state).toEqual(840);
});

tap.test('exposes IamMeter read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IammeterIntegration();
  const alias = new HomeAssistantIammeterIntegration();
  expect(alias instanceof IammeterIntegration).toBeTrue();
  expect(alias.domain).toEqual('iammeter');
  expect(integration.status).toEqual('read-only-runtime');
  expect(iammeterProfile.metadata.configFlow).toEqual(false);
  expect(iammeterProfile.metadata.qualityScale).toEqual('legacy');
  expect(iammeterProfile.metadata.requirements).toEqual(['iammeter==0.2.1']);

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

  expect(status.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('IamMeter WEM3080T');

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

export default tap.start();
