import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GreeneyeMonitorClient, GreeneyeMonitorConfigFlow, GreeneyeMonitorIntegration, GreeneyeMonitorMapper, HomeAssistantGreeneyeMonitorIntegration, createGreeneyeMonitorDiscoveryDescriptor, greeneyeMonitorProfile, type IGreeneyeMonitorSnapshot, type TGreeneyeMonitorRawData } from '../../ts/integrations/greeneye_monitor/index.js';

const rawData: TGreeneyeMonitorRawData = {
  device: {
    id: 'gem-00012345',
    name: 'GEM 00012345',
    manufacturer: 'Brultech',
    model: 'GreenEye Monitor',
    serialNumber: '00012345',
  },
  entities: [
    { id: 'channel_1_power', name: 'Channel 1 Power', platform: 'sensor', state: 512, unit: 'W', deviceClass: 'power', attributes: { watt_seconds: 123456 } },
    { id: 'voltage_1', name: 'Voltage 1', platform: 'sensor', state: 120.4, unit: 'V', deviceClass: 'voltage' },
    { id: 'temperature_1', name: 'Temperature 1', platform: 'sensor', state: 21.5, unit: 'C', deviceClass: 'temperature' },
    { id: 'pulse_counter_1', name: 'Water Meter', platform: 'sensor', state: 12.3, unit: 'L/min', attributes: { pulses: 42 } },
  ],
  packet: {
    channels: 48,
    pulseCounters: 4,
  },
};

tap.test('matches manual GreenEye Monitor candidates and creates config flow output', async () => {
  const descriptor = createGreeneyeMonitorDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'greeneye_monitor-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'gem-00012345', name: 'GEM 00012345', metadata: { rawData } }, {});

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

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

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

tap.test('maps GreenEye Monitor raw snapshots to runtime devices and entities', async () => {
  const client = new GreeneyeMonitorClient({ name: 'GreenEye Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = GreeneyeMonitorMapper.toSnapshotFromRaw({ name: 'GreenEye Runtime' }, rawData);
  const devices = GreeneyeMonitorMapper.toDevices(mappedSnapshot);
  const entities = GreeneyeMonitorMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('greeneye_monitor');
  expect(devices[0].manufacturer).toEqual('Brultech');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.gem_00012345_channel_1_power')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'sensor.gem_00012345_temperature_1')).toBeTrue();
});

tap.test('exposes GreenEye Monitor read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GreeneyeMonitorIntegration();
  const alias = new HomeAssistantGreeneyeMonitorIntegration();
  expect(alias instanceof GreeneyeMonitorIntegration).toBeTrue();
  expect(alias.domain).toEqual('greeneye_monitor');
  expect(integration.status).toEqual('read-only-runtime');
  expect(greeneyeMonitorProfile.metadata.configFlow).toEqual(false);
  expect(greeneyeMonitorProfile.metadata.qualityScale).toEqual('legacy');
  expect(greeneyeMonitorProfile.metadata.requirements).toEqual(['greeneye_monitor==3.0.3']);

  const runtime = await integration.setup({ name: 'GreenEye Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'greeneye_monitor', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'greeneye_monitor', service: 'refresh', target: {} });
  const snapshot = status.data as IGreeneyeMonitorSnapshot;

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

  const command = await runtime.callService!({ domain: 'greeneye_monitor', 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();
