import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantIhcIntegration, IhcClient, IhcConfigFlow, IhcIntegration, IhcMapper, createIhcDiscoveryDescriptor, ihcProfile, type IIhcSnapshot, type TIhcRawData } from '../../ts/integrations/ihc/index.js';

const rawData: TIhcRawData = {
  device: {
    id: 'ihc-controller-123456',
    name: 'Main IHC Controller',
    manufacturer: 'Schneider Electric',
    model: 'IHC Controller',
    serialNumber: '123456',
    attributes: {
      url: 'http://ihc-controller.local',
      controllerId: '123456',
    },
  },
  entities: [
    { id: 'motion_1001', name: 'Hall Motion', platform: 'binary_sensor', state: true, deviceClass: 'motion', attributes: { ihcId: 1001 } },
    { id: 'light_2001', name: 'Hall Light', platform: 'light', state: true, writable: true, attributes: { ihcId: 2001, brightness: 180 } },
    { id: 'temperature_3001', name: 'Living Room Temperature', platform: 'sensor', state: 21.4, unit: 'C', deviceClass: 'temperature', stateClass: 'measurement', attributes: { ihcId: 3001 } },
    { id: 'switch_4001', name: 'Pump Switch', platform: 'switch', state: false, writable: true, attributes: { ihcId: 4001 } },
  ],
};

tap.test('matches manual IHC candidates and creates config flow output', async () => {
  const descriptor = createIhcDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ihc-manual-match');
  const result = await matcher!.matches({ id: 'ihc-controller-123456', name: 'Main IHC Controller', metadata: { url: 'http://ihc-controller.local', rawData } }, {});

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

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

  const done = await (await new IhcConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('ihc-controller-123456');
  expect(done.config?.metadata?.url).toEqual('http://ihc-controller.local');
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ihc');
  expect(devices[0].manufacturer).toEqual('Schneider Electric');
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.main_ihc_controller_motion_1001')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'light.main_ihc_controller_light_2001')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.main_ihc_controller_switch_4001')).toBeTrue();
});

tap.test('exposes IHC read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new IhcIntegration();
  const alias = new HomeAssistantIhcIntegration();
  expect(alias instanceof IhcIntegration).toBeTrue();
  expect(alias.domain).toEqual('ihc');
  expect(integration.status).toEqual('read-only-runtime');
  expect(ihcProfile.metadata.configFlow).toEqual(false);
  expect(ihcProfile.metadata.qualityScale).toEqual('legacy');
  expect(ihcProfile.metadata.requirements).toEqual(['defusedxml==0.7.1', 'ihcsdk==2.8.5']);

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

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

  const command = await runtime.callService!({ domain: 'ihc', service: 'set_runtime_value_bool', target: {}, data: { ihc_id: 2001, value: true } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
