import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FibaroClient, FibaroConfigFlow, FibaroIntegration, FibaroMapper, HomeAssistantFibaroIntegration, createFibaroDiscoveryDescriptor, fibaroProfile, type IFibaroSnapshot } from '../../ts/integrations/fibaro/index.js';

const rawData = {
  info: {
    serial_number: 'HC3-12345',
    hc_name: 'Home Center 3',
    manufacturer_name: 'Fibaro',
    model_name: 'Home Center 3',
    current_version: '5.150.18',
    mac_address: '00:11:22:33:44:55',
  },
  devices: [
    { fibaro_id: 11, name: 'Temperature', room_name: 'Kitchen', type: 'com.fibaro.temperatureSensor', value: '21.4', unit: 'C', properties: { value: '21.4' } },
    { fibaro_id: 12, name: 'Motion', room_name: 'Hall', type: 'com.fibaro.motionSensor', value: true, properties: { value: true } },
    { fibaro_id: 13, name: 'Wall Plug', room_name: 'Living', type: 'com.fibaro.binarySwitch', value: false, actions: ['turnOn', 'turnOff'], properties: { value: false, power: '12.5', energy: '1.2' } },
  ],
  scenes: [
    { fibaro_id: 50, name: 'Evening', room_id: 1, visible: true },
  ],
};

tap.test('matches manual Fibaro candidates and creates config flow output', async () => {
  const descriptor = createFibaroDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'fibaro-manual-match');
  const result = await matcher!.matches({ host: 'fibaro.local', name: 'Fibaro Home Center', metadata: { rawData } }, {});

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

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

  const done = await (await new FibaroConfigFlow().start(result.candidate!, {})).submit!({ username: 'admin', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('fibaro.local');
  expect(done.config?.path).toEqual('/api/');
  expect(done.config?.username).toEqual('admin');
});

tap.test('maps Fibaro raw snapshots to hub devices and entities', async () => {
  const client = new FibaroClient({ host: 'fibaro.local', rawData });
  const snapshot = await client.getSnapshot();
  const devices = FibaroMapper.toDevices(snapshot);
  const entities = FibaroMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.device.serialNumber).toEqual('HC3-12345');
  expect(devices[0].integrationDomain).toEqual('fibaro');
  expect(devices[0].manufacturer).toEqual('Fibaro');
  expect(entities.length).toEqual(6);
  expect(entities.some((entityArg) => entityArg.attributes?.deviceClass === 'temperature')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'button')).toBeTrue();
});

tap.test('exposes Fibaro read-only runtime, HA alias, and explicit unsupported control without executor', async () => {
  const integration = new FibaroIntegration();
  const alias = new HomeAssistantFibaroIntegration();
  expect(alias.domain).toEqual('fibaro');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fibaroProfile.metadata.configFlow).toEqual(true);
  expect(fibaroProfile.metadata.requirements).toEqual(['pyfibaro==0.8.3']);
  expect(Object.prototype.hasOwnProperty.call(fibaroProfile.metadata, 'qualityScale')).toBeTrue();
  expect(fibaroProfile.metadata.qualityScale).toBeUndefined();

  const runtime = await integration.setup({ host: 'fibaro.local', rawData }, {});
  const status = await runtime.callService!({ domain: 'fibaro', service: 'status', target: {} });
  const snapshot = status.data as IFibaroSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Home Center 3');

  const command = await runtime.callService!({ domain: 'fibaro', service: 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
