import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GeniushubClient, GeniushubConfigFlow, GeniushubIntegration, GeniushubMapper, HomeAssistantGeniushubIntegration, createGeniushubDiscoveryDescriptor, geniushubProfile, type IGeniushubSnapshot, type TGeniushubRawData } from '../../ts/integrations/geniushub/index.js';

const rawData: TGeniushubRawData = {
  hubUid: 'hub-001',
  zones: [
    { id: 1, name: 'Kitchen', type: 'radiator', mode: 'timer', temperature: 21.2, setpoint: 20.5, occupied: true, output: 1 },
    { id: 2, name: 'Hot Water Pump', type: 'on / off', mode: 'override', setpoint: 1 },
  ],
  devices: [
    {
      id: 11,
      type: 'Receiver',
      data: {
        assignedZones: [{ name: 'Kitchen' }],
        state: {
          outputOnOff: true,
          batteryLevel: 88,
        },
      },
    },
  ],
  issues: [
    { level: 'warning', description: 'Receiver battery low' },
  ],
};

tap.test('matches manual Genius Hub candidates and creates config flow output', async () => {
  const descriptor = createGeniushubDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'geniushub-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'hub-001', name: 'Genius Hub', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(devices[0].integrationDomain).toEqual('geniushub');
  expect(entities.some((entityArg) => entityArg.id === 'climate.genius_hub_zone_1')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.genius_hub_zone_2')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'sensor.genius_hub_device_11_battery')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.genius_hub_device_11_output')).toBeTrue();
});

tap.test('exposes Genius Hub read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GeniushubIntegration();
  const alias = new HomeAssistantGeniushubIntegration();
  expect(alias instanceof GeniushubIntegration).toBeTrue();
  expect(alias.domain).toEqual('geniushub');
  expect(integration.status).toEqual('read-only-runtime');
  expect(geniushubProfile.metadata.configFlow).toEqual(true);
  expect(geniushubProfile.metadata.requirements).toEqual(['geniushub-client==0.7.1']);
  expect(geniushubProfile.metadata.codeowners).toEqual(['@manzanotti']);

  const runtime = await integration.setup({ name: 'Genius Hub', rawData }, {});
  const status = await runtime.callService!({ domain: 'geniushub', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'geniushub', service: 'refresh', target: {} });
  const snapshot = status.data as IGeniushubSnapshot;

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

  const command = await runtime.callService!({ domain: 'geniushub', service: 'set_zone_mode', target: { entityId: 'climate.genius_hub_zone_1' }, data: { mode: 'off' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
