import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GreenwaveClient, GreenwaveConfigFlow, GreenwaveIntegration, GreenwaveMapper, HomeAssistantGreenwaveIntegration, createGreenwaveDiscoveryDescriptor, greenwaveProfile, type IGreenwaveSnapshot, type TGreenwaveRawData } from '../../ts/integrations/greenwave/index.js';

const rawData: TGreenwaveRawData = {
  device: {
    id: 'greenwave-gateway',
    name: 'Greenwave Gateway',
    manufacturer: 'Greenwave Reality',
    model: 'TCP Connected gateway',
    host: '192.0.2.30',
  },
  entities: [
    { id: 'kitchen_lamp', name: 'Kitchen Lamp', platform: 'light', state: true, writable: true, attributes: { did: 3, brightness: 191, available: true } },
    { id: 'hallway_lamp', name: 'Hallway Lamp', platform: 'light', state: false, writable: true, attributes: { did: 4, brightness: 0, available: true } },
  ],
  bulbs: {
    '3': { did: '3', name: 'Kitchen Lamp', state: '1', level: '75' },
    '4': { did: '4', name: 'Hallway Lamp', state: '0', level: '0' },
  },
};

tap.test('matches manual Greenwave candidates and creates config flow output', async () => {
  const descriptor = createGreenwaveDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'greenwave-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: '192.0.2.30', name: 'Greenwave Gateway', metadata: { rawData, version: 3 } }, {});

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('greenwave');
  expect(devices[0].manufacturer).toEqual('Greenwave Reality');
  expect(entities.some((entityArg) => entityArg.id === 'light.greenwave_gateway_kitchen_lamp')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.id === 'light.greenwave_gateway_hallway_lamp')).toBeTrue();
});

tap.test('exposes Greenwave read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GreenwaveIntegration();
  const alias = new HomeAssistantGreenwaveIntegration();
  expect(alias instanceof GreenwaveIntegration).toBeTrue();
  expect(alias.domain).toEqual('greenwave');
  expect(integration.status).toEqual('read-only-runtime');
  expect(greenwaveProfile.metadata.configFlow).toEqual(false);
  expect(greenwaveProfile.metadata.qualityScale).toEqual('legacy');
  expect(greenwaveProfile.metadata.requirements).toEqual(['greenwavereality==0.5.1']);

  const runtime = await integration.setup({ name: 'Greenwave Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'greenwave', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'greenwave', service: 'refresh', target: {} });
  const snapshot = status.data as IGreenwaveSnapshot;

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

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

export default tap.start();
