import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EcoforestClient, EcoforestConfigFlow, EcoforestIntegration, EcoforestMapper, HomeAssistantEcoforestIntegration, ecoforestProfile, createEcoforestDiscoveryDescriptor, type IEcoforestSnapshot } from '../../ts/integrations/ecoforest/index.js';

const rawData = {
  device: {
    id: 'eco-forest-5678',
    name: 'Ecoforest stove',
    model: 'Vigo III',
    serialNumber: 'eco-forest-5678',
  },
  entities: [
    {
      id: 'temperature',
      name: 'Temperature',
      platform: 'sensor',
      state: 22.4,
      unit: 'C',
      deviceClass: 'temperature',
    },
    {
      id: 'status',
      name: 'Status',
      platform: 'sensor',
      state: 'on',
    },
    {
      id: 'power_level',
      name: 'Power level',
      platform: 'number',
      state: 5,
      writable: true,
    },
    {
      id: 'status_switch',
      name: 'Status switch',
      platform: 'switch',
      state: true,
      writable: true,
    },
  ],
};

tap.test('defines the Ecoforest simple-local profile and HA alias', async () => {
  const integration = new HomeAssistantEcoforestIntegration();

  expect(integration).toBeInstanceOf(EcoforestIntegration);
  expect(integration.domain).toEqual('ecoforest');
  expect(integration.status).toEqual('control-runtime');
  expect(ecoforestProfile.metadata.upstreamPath).toEqual('homeassistant/components/ecoforest');
  expect(ecoforestProfile.metadata.qualityScale).toEqual(undefined);
  expect(ecoforestProfile.metadata.requirements).toEqual(['pyecoforest==0.4.0']);
  expect(ecoforestProfile.metadata.configFlow).toBeTrue();
  expect(ecoforestProfile.serviceDomains).toEqual(['number', 'switch']);
});

tap.test('matches manual Ecoforest candidates and creates config flow output', async () => {
  const descriptor = createEcoforestDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ecoforest-manual-match');
  const result = await matcher!.matches({ host: 'ecoforest.local', name: 'Ecoforest stove', metadata: { rawData } }, {});

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

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

  const done = await (await new EcoforestConfigFlow().start(result.candidate!, {})).submit!({ username: 'user', password: 'pass' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('ecoforest.local');
  expect(done.config?.username).toEqual('user');
});

tap.test('maps Ecoforest raw snapshots to runtime devices and entities', async () => {
  const client = new EcoforestClient({ name: 'Ecoforest Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = EcoforestMapper.toDevices(snapshot);
  const entities = EcoforestMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ecoforest');
  expect(devices[0].manufacturer).toEqual('Ecoforest');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.ecoforest_stove_temperature')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'number.ecoforest_stove_power_level')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'switch.ecoforest_stove_status_switch')).toBeTrue();
});

tap.test('exposes Ecoforest runtime services without fake live control', async () => {
  const runtime = await new EcoforestIntegration().setup({ name: 'Ecoforest Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'ecoforest', service: 'status', target: {} });
  const snapshot = status.data as IEcoforestSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.entities()).some((entityArg) => entityArg.platform === 'number')).toBeTrue();

  const liveCommand = await runtime.callService!({ domain: 'number', service: 'set_value', target: {}, data: { value: 6 } });
  expect(liveCommand.success).toBeFalse();
  expect(liveCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();

  const executorRuntime = await new EcoforestIntegration().setup({
    name: 'Ecoforest Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'switch', service: 'turn_on', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
