import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EcowittClient, EcowittConfigFlow, EcowittIntegration, EcowittMapper, HomeAssistantEcowittIntegration, ecowittProfile, createEcowittDiscoveryDescriptor, type IEcowittSnapshot } from '../../ts/integrations/ecowitt/index.js';

const rawData = {
  device: {
    id: 'gw1000-90ab',
    name: 'Ecowitt GW1000',
    model: 'GW1000',
    serialNumber: 'gw1000-90ab',
  },
  entities: [
    {
      id: 'tempinf',
      name: 'Indoor temperature',
      platform: 'sensor',
      state: 21.7,
      unit: 'C',
      deviceClass: 'temperature',
    },
    {
      id: 'humidityin',
      name: 'Indoor humidity',
      platform: 'sensor',
      state: 48,
      unit: '%',
      deviceClass: 'humidity',
    },
    {
      id: 'leak_ch1',
      name: 'Leak channel 1',
      platform: 'binary_sensor',
      state: false,
      deviceClass: 'moisture',
    },
  ],
};

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

  expect(integration).toBeInstanceOf(EcowittIntegration);
  expect(integration.domain).toEqual('ecowitt');
  expect(integration.status).toEqual('read-only-runtime');
  expect(ecowittProfile.metadata.upstreamPath).toEqual('homeassistant/components/ecowitt');
  expect(ecowittProfile.metadata.qualityScale).toEqual(undefined);
  expect(ecowittProfile.metadata.requirements).toEqual(['aioecowitt==2025.9.2']);
  expect(ecowittProfile.metadata.dependencies).toEqual(['webhook']);
  expect(ecowittProfile.metadata.configFlow).toBeTrue();
});

tap.test('matches manual Ecowitt candidates and creates config flow output', async () => {
  const descriptor = createEcowittDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ecowitt-manual-match');
  const result = await matcher!.matches({ name: 'Ecowitt GW1000', metadata: { rawData } }, {});

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

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

  const done = await (await new EcowittConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.transport).toEqual('snapshot');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('ecowitt');
  expect(devices[0].manufacturer).toEqual('Ecowitt');
  expect(entities.some((entityArg) => entityArg.id === 'sensor.ecowitt_gw1000_tempinf')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'binary_sensor.ecowitt_gw1000_leak_ch1')).toBeTrue();
});

tap.test('exposes Ecowitt read-only runtime and rejects unsupported control', async () => {
  const runtime = await new EcowittIntegration().setup({ name: 'Ecowitt Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'ecowitt', service: 'status', target: {} });
  const snapshot = status.data as IEcowittSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Ecowitt GW1000');

  const controlCommand = await runtime.callService!({ domain: 'ecowitt', service: 'turn_on', target: {} });
  expect(controlCommand.success).toBeFalse();
  expect(controlCommand.error?.includes('requires an injected client.execute() or commandExecutor')).toBeTrue();
  await runtime.destroy();
});

export default tap.start();
