import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHomeeIntegration, HomeeClient, HomeeConfigFlow, HomeeIntegration, HomeeMapper, createHomeeDiscoveryDescriptor, homeeProfile, type IHomeeSnapshot, type THomeeRawData } from '../../ts/integrations/homee/index.js';

const rawData: THomeeRawData = {
  settings: {
    uid: 'homee-1234',
    homee_name: 'Homee Cube',
    mac_address: '00:11:22:33:44:55',
    version: '2.40.0',
  },
  connected: true,
  nodes: [
    {
      id: 1,
      name: 'Living Room Thermostat',
      profile: 'room_thermostat',
      state: 'available',
      attributes: [
        { id: 1, name: 'Temperature', type: 'temperature', value: 21.5, unit: 'C', platform: 'sensor' },
        { id: 2, name: 'Target Temperature', type: 'target_temperature', value: 20, unit: 'C', platform: 'climate', writable: true },
      ],
    },
    {
      id: 2,
      name: 'Kitchen Plug',
      profile: 'metering_switch',
      state: 'available',
      attributes: [
        { id: 1, name: 'Switch', type: 'on_off', value: true, platform: 'switch', writable: true },
        { id: 2, name: 'Energy', type: 'energy', value: 1.2, unit: 'kWh' },
      ],
    },
  ],
};

tap.test('matches manual Homee candidates and creates config flow output', async () => {
  const descriptor = createHomeeDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homee-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: '192.0.2.50', id: 'homee-1234', name: 'Homee Cube', metadata: { rawData } }, {});

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

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

  const done = await (await new HomeeConfigFlow().start(result.candidate!, {})).submit!({ username: 'user', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.0.2.50');
  expect(done.config?.username).toEqual('user');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Homee raw snapshots to runtime devices and entities', async () => {
  const client = new HomeeClient({ name: 'Homee Cube', host: '192.0.2.50', rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = HomeeMapper.toSnapshotFromRaw({ name: 'Homee Cube', host: '192.0.2.50' }, rawData);
  const devices = HomeeMapper.toDevices(mappedSnapshot);
  const entities = HomeeMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('homee');
  expect(devices[0].manufacturer).toEqual('homee');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.homee_cube_living_room_thermostat_temperature')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.homee_cube_kitchen_plug_switch')).toBeTrue();
});

tap.test('exposes Homee read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HomeeIntegration();
  const alias = new HomeAssistantHomeeIntegration();
  expect(alias instanceof HomeeIntegration).toBeTrue();
  expect(alias.domain).toEqual('homee');
  expect(integration.status).toEqual('read-only-runtime');
  expect(homeeProfile.metadata.configFlow).toEqual(true);
  expect(homeeProfile.metadata.qualityScale).toEqual('silver');
  expect(homeeProfile.metadata.requirements).toEqual(['pyHomee==1.3.8']);

  const runtime = await integration.setup({ name: 'Homee Cube', host: '192.0.2.50', rawData }, {});
  const status = await runtime.callService!({ domain: 'homee', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'homee', service: 'refresh', target: {} });
  const snapshot = status.data as IHomeeSnapshot;

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

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

export default tap.start();
