import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EphemberClient, EphemberConfigFlow, EphemberIntegration, EphemberMapper, HomeAssistantEphemberIntegration, createEphemberDiscoveryDescriptor, ephemberProfile, type IEphemberSnapshot } from '../../ts/integrations/ephember/index.js';

const rawData = {
  device: {
    id: 'eph-ember-home-1',
    name: 'EPH Ember Home',
    manufacturer: 'EPH Controls',
    model: 'Ember',
  },
  entities: [
    { id: 'living_room', name: 'Living Room', platform: 'climate', state: 'heat_cool', writable: true, attributes: { currentTemperature: 20.5, targetTemperature: 21, hvacAction: 'heating' } },
    { id: 'hot_water', name: 'Hot Water', platform: 'climate', state: 'off', writable: true, attributes: { hotWater: true, hvacAction: 'idle' } },
  ],
};

tap.test('matches manual Ephember candidates and creates config flow output', async () => {
  const descriptor = createEphemberDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ephember-manual-match');
  const result = await matcher!.matches({ name: 'EPH Controls Ember', metadata: { rawData } }, {});

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

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

  const done = await (await new EphemberConfigFlow().start(result.candidate!, {})).submit!({ username: 'user@example.com', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.username).toEqual('user@example.com');
  expect(done.config?.transport).toEqual('snapshot');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Ephember raw snapshots to runtime devices and entities', async () => {
  const client = new EphemberClient({ name: 'EPH Runtime', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EphemberMapper.toDevices(snapshot);
  const entities = EphemberMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ephember');
  expect(devices[0].manufacturer).toEqual('EPH Controls');
  expect(entities.length).toEqual(2);
  expect(entities[0].platform).toEqual('climate');
});

tap.test('exposes Ephember runtime services, HA alias, and unsupported control without executor', async () => {
  const integration = new EphemberIntegration();
  const alias = new HomeAssistantEphemberIntegration();
  expect(alias instanceof EphemberIntegration).toBeTrue();
  expect(alias.domain).toEqual('ephember');
  expect(integration.status).toEqual('control-runtime');
  expect(ephemberProfile.metadata.requirements).toEqual(['pyephember2==0.4.12']);
  expect(ephemberProfile.metadata.configFlow).toEqual(false);

  const runtime = await integration.setup({ name: 'EPH Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'ephember', service: 'status', target: {} });
  const snapshot = status.data as IEphemberSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('EPH Ember Home');
  expect((await runtime.callService!({ domain: 'ephember', service: 'refresh', target: {} })).success).toBeTrue();

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

export default tap.start();
