import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FritzboxClient, FritzboxConfigFlow, FritzboxIntegration, FritzboxMapper, HomeAssistantFritzboxIntegration, createFritzboxDiscoveryDescriptor, fritzboxProfile, type IFritzboxSnapshot, type TFritzboxRawData } from '../../ts/integrations/fritzbox/index.js';

const rawData: TFritzboxRawData = {
  device: {
    id: 'fritz-ain-1',
    name: 'FRITZ SmartHome Hub',
    manufacturer: 'AVM',
    model: 'FRITZ!Box 7590',
    host: '192.0.2.20',
  },
  entities: [
    { id: 'outlet', name: 'Outlet', platform: 'switch', state: true, writable: true, attributes: { ain: '08761 0000001' } },
    { id: 'temperature', name: 'Temperature', platform: 'sensor', state: 21.5, unit: 'C', deviceClass: 'temperature' },
    { id: 'window_open', name: 'Window Open', platform: 'binary_sensor', state: false, deviceClass: 'window' },
    { id: 'bulb', name: 'Bulb', platform: 'light', state: true, writable: true, attributes: { brightness: 180, colorMode: 'brightness' } },
    { id: 'thermostat', name: 'Thermostat', platform: 'climate', state: 'heat', writable: true, attributes: { currentTemperature: 20.5, targetTemperature: 22, hvacMode: 'heat', presetMode: 'comfort' } },
    { id: 'blind', name: 'Blind', platform: 'cover', state: 'open', writable: true, attributes: { position: 75 } },
    { id: 'template', name: 'Template', platform: 'button', state: 'ready', writable: true },
  ],
};

tap.test('matches manual FRITZ!SmartHome candidates and creates config flow output', async () => {
  const descriptor = createFritzboxDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'fritzbox-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'fritz-ain-1', name: 'FRITZ SmartHome Hub', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('fritzbox');
  expect(devices[0].manufacturer).toEqual('AVM');
  expect(entities.some((entityArg) => entityArg.id === 'switch.fritz_smarthome_hub_outlet')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'climate.fritz_smarthome_hub_thermostat')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'button.fritz_smarthome_hub_template')).toBeTrue();
});

tap.test('exposes FRITZ!SmartHome read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FritzboxIntegration();
  const alias = new HomeAssistantFritzboxIntegration();
  expect(alias instanceof FritzboxIntegration).toBeTrue();
  expect(alias.domain).toEqual('fritzbox');
  expect(integration.status).toEqual('read-only-runtime');
  expect(fritzboxProfile.metadata.configFlow).toEqual(true);
  expect(fritzboxProfile.metadata.integrationType).toEqual('hub');
  expect(fritzboxProfile.metadata.requirements).toEqual(['pyfritzhome==0.6.20']);

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

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

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

export default tap.start();
