import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FlexitClient, FlexitConfigFlow, FlexitIntegration, FlexitMapper, HomeAssistantFlexitIntegration, createFlexitDiscoveryDescriptor, flexitProfile, type IFlexitSnapshot, type TFlexitRawData } from '../../ts/integrations/flexit/index.js';

const rawData: TFlexitRawData = {
  device: {
    id: 'flexit-ci66',
    name: 'Flexit CI66',
    manufacturer: 'Flexit',
    model: 'CI66 Modbus adapter',
  },
  entities: [
    {
      id: 'climate',
      name: 'Climate',
      platform: 'climate',
      state: 'cool',
      writable: true,
      attributes: {
        currentTemperature: 21.1,
        targetTemperature: 19.5,
        fanMode: 'Medium',
        fanModes: ['Off', 'Low', 'Medium', 'High'],
        hvacAction: 'fan',
        hvacModes: ['cool'],
      },
    },
    { id: 'filter_hours', name: 'Filter Hours', platform: 'sensor', state: 124, unit: 'h' },
    { id: 'filter_alarm', name: 'Filter Alarm', platform: 'binary_sensor', state: false, deviceClass: 'problem' },
    { id: 'heat_recovery', name: 'Heat Recovery', platform: 'sensor', state: 35, unit: '%' },
    { id: 'outdoor_air_temp', name: 'Outdoor Air Temp', platform: 'sensor', state: 8.4, unit: 'C', deviceClass: 'temperature' },
  ],
  registers: {
    holding8TargetTemperature: 195,
    holding17FanMode: 2,
    input9CurrentTemperature: 211,
  },
};

tap.test('matches manual Flexit candidates and creates config flow output', async () => {
  const descriptor = createFlexitDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'flexit-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'flexit-ci66', name: 'Flexit CI66', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('flexit');
  expect(devices[0].manufacturer).toEqual('Flexit');
  expect(entities.some((entityArg) => entityArg.id === 'climate.flexit_ci66_climate')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.flexit_ci66_filter_alarm')).toBeTrue();
});

tap.test('exposes Flexit read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FlexitIntegration();
  const alias = new HomeAssistantFlexitIntegration();
  expect(alias instanceof FlexitIntegration).toBeTrue();
  expect(alias.domain).toEqual('flexit');
  expect(integration.status).toEqual('read-only-runtime');
  expect(flexitProfile.metadata.configFlow).toEqual(false);
  expect(flexitProfile.metadata.qualityScale).toEqual('legacy');
  expect(flexitProfile.metadata.dependencies).toEqual(['modbus']);

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

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

  const command = await runtime.callService!({ domain: 'climate', service: 'set_temperature', target: { entityId: 'climate.flexit_runtime_climate' }, data: { temperature: 20 } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
