import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantHomekitIntegration, HomekitClient, HomekitConfigFlow, HomekitIntegration, HomekitMapper, createHomekitDiscoveryDescriptor, homekitProfile, type IHomekitSnapshot, type THomekitRawData } from '../../ts/integrations/homekit/index.js';

const rawData: THomekitRawData = {
  device: {
    id: 'homekit-bridge',
    name: 'HomeKit Bridge',
    manufacturer: 'Home Assistant',
    model: 'HomeKit Bridge',
  },
  entities: [
    { id: 'living_room_lamp', name: 'Living Room Lamp', platform: 'light', state: true, writable: true, attributes: { brightness: 180, homekitService: 'Lightbulb' } },
    { id: 'front_door', name: 'Front Door', platform: 'binary_sensor', state: false, deviceClass: 'door', attributes: { homekitService: 'ContactSensor' } },
    { id: 'thermostat', name: 'Thermostat', platform: 'climate', state: 'heat', writable: true, attributes: { currentTemperature: 20.5, targetTemperature: 21 } },
  ],
  mode: 'bridge',
  port: 21064,
};

tap.test('matches manual HomeKit candidates and creates config flow output', async () => {
  const descriptor = createHomekitDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'homekit-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'homekit-bridge', name: 'HomeKit Bridge', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('homekit');
  expect(devices[0].manufacturer).toEqual('Home Assistant');
  expect(entities.some((entityArg) => entityArg.id === 'light.homekit_bridge_living_room_lamp')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.homekit_bridge_front_door')).toBeTrue();
});

tap.test('exposes HomeKit read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new HomekitIntegration();
  const alias = new HomeAssistantHomekitIntegration();
  expect(alias instanceof HomekitIntegration).toBeTrue();
  expect(alias.domain).toEqual('homekit');
  expect(integration.status).toEqual('read-only-runtime');
  expect(homekitProfile.metadata.configFlow).toEqual(true);
  expect(homekitProfile.metadata.requirements).toEqual(['HAP-python==5.0.0', 'fnv-hash-fast==2.0.2', 'homekit-audio-proxy==1.2.1', 'PyQRCode==1.2.1', 'base36==0.1.1']);
  expect(homekitProfile.metadata.afterDependencies).toEqual(['camera', 'zeroconf']);

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

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

  const command = await runtime.callService!({ domain: 'homekit', service: 'reset_accessory', target: {}, data: { entity_id: ['light.homekit_bridge_living_room_lamp'] } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
