import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FuturenowClient, FuturenowConfigFlow, FuturenowIntegration, FuturenowMapper, HomeAssistantFuturenowIntegration, createFuturenowDiscoveryDescriptor, futurenowProfile, type IFuturenowSnapshot, type TFuturenowRawData } from '../../ts/integrations/futurenow/index.js';

const rawData: TFuturenowRawData = {
  device: {
    id: 'fnip-controller',
    name: 'FutureNow Controller',
    manufacturer: 'FutureNow',
    model: 'FNIP8x10a',
    host: '192.0.2.30',
    port: 1024,
  },
  entities: [
    { id: 'kitchen', name: 'Kitchen', platform: 'light', state: true, writable: true, attributes: { channel: '1', brightness: 204, dimmable: true, driver: 'FNIP8x10a' } },
    { id: 'hallway', name: 'Hallway', platform: 'light', state: false, writable: true, attributes: { channel: '2', brightness: 0, dimmable: false, driver: 'FNIP8x10a' } },
  ],
};

tap.test('matches manual FutureNow candidates and creates config flow output', async () => {
  const descriptor = createFuturenowDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'futurenow-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'fnip-controller', name: 'FutureNow Controller', metadata: { rawData } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('futurenow');
  expect(devices[0].manufacturer).toEqual('FutureNow');
  expect(entities.some((entityArg) => entityArg.id === 'light.futurenow_controller_kitchen')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'light.futurenow_controller_hallway')).toBeTrue();
});

tap.test('exposes FutureNow read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new FuturenowIntegration();
  const alias = new HomeAssistantFuturenowIntegration();
  expect(alias instanceof FuturenowIntegration).toBeTrue();
  expect(alias.domain).toEqual('futurenow');
  expect(integration.status).toEqual('read-only-runtime');
  expect(futurenowProfile.metadata.configFlow).toEqual(false);
  expect(futurenowProfile.metadata.qualityScale).toEqual('legacy');
  expect(futurenowProfile.metadata.requirements).toEqual(['pyfnip==0.2']);

  const runtime = await integration.setup({ name: 'FutureNow Controller', rawData }, {});
  const status = await runtime.callService!({ domain: 'futurenow', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'futurenow', service: 'refresh', target: {} });
  const snapshot = status.data as IFuturenowSnapshot;

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

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

export default tap.start();
