import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHrEnergyQubeIntegration, HrEnergyQubeClient, HrEnergyQubeConfigFlow, HrEnergyQubeIntegration, HrEnergyQubeMapper, createHrEnergyQubeDiscoveryDescriptor, hrEnergyQubeProfile, type IHrEnergyQubeSnapshot, type THrEnergyQubeRawData } from '../../ts/integrations/hr_energy_qube/index.js';

const rawData: THrEnergyQubeRawData = {
  device: {
    id: 'qube-heat-pump',
    name: 'Qube Heat Pump',
    manufacturer: 'Qube',
    model: 'Heat Pump',
    host: '192.0.2.10',
    port: 502,
  },
  entities: [
    { id: 'temp_supply', name: 'Supply temperature CH', platform: 'sensor', state: 35.2, unit: 'C', deviceClass: 'temperature', stateClass: 'measurement' },
    { id: 'power_electric', name: 'Electric power', platform: 'sensor', state: 1200, unit: 'W', deviceClass: 'power', stateClass: 'measurement' },
    { id: 'status_heatpump', name: 'Heat pump status', platform: 'sensor', state: 'heating', deviceClass: 'enum' },
    { id: 'alarm_global', name: 'Global alarm', platform: 'binary_sensor', state: false, deviceClass: 'problem' },
  ],
  registers: {
    statusCode: 16,
    softwareVersion: '1.8.0',
  },
};

tap.test('matches manual Qube candidates and creates config flow output', async () => {
  const descriptor = createHrEnergyQubeDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'hr_energy_qube-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'qube-heat-pump', name: 'Qube heat pump', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('hr_energy_qube');
  expect(devices[0].manufacturer).toEqual('Qube');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.qube_heat_pump_temp_supply')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.qube_heat_pump_alarm_global')).toBeTrue();
});

tap.test('exposes Qube read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HrEnergyQubeIntegration();
  const alias = new HomeAssistantHrEnergyQubeIntegration();
  expect(alias instanceof HrEnergyQubeIntegration).toBeTrue();
  expect(alias.domain).toEqual('hr_energy_qube');
  expect(integration.status).toEqual('read-only-runtime');
  expect(hrEnergyQubeProfile.metadata.configFlow).toEqual(true);
  expect(hrEnergyQubeProfile.metadata.qualityScale).toEqual('bronze');
  expect(hrEnergyQubeProfile.metadata.requirements).toEqual(['python-qube-heatpump==1.8.0']);

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

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

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