import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLifxIntegration, LifxClient, LifxConfigFlow, LifxIntegration, LifxMapper, createLifxDiscoveryDescriptor, lifxProfile, type ILifxSnapshot, type TLifxRawData } from '../../ts/integrations/lifx/index.js';

const rawData: TLifxRawData = {
  device: {
    id: 'lifx-device-1',
    name: "LIFX Device",
    manufacturer: "LIFX",
    model: "LIFX local integration",
    serialNumber: 'lifx-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "binary_sensor", state: true, attributes: { domain: "lifx" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual LIFX candidates and creates config flow output', async () => {
  const descriptor = createLifxDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'lifx-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'lifx-device-1', name: "LIFX Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("lifx");

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

  const done = await (await new LifxConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('lifx-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("lifx");
  expect(devices[0].manufacturer).toEqual("LIFX");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "lifx" && entityArg.platform === "binary_sensor")).toBeTrue();
});

tap.test('exposes LIFX runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LifxIntegration();
  const alias = new HomeAssistantLifxIntegration();
  expect(alias instanceof LifxIntegration).toBeTrue();
  expect(alias.domain).toEqual("lifx");
  expect(integration.status).toEqual("control-runtime");
  expect(lifxProfile.metadata.configFlow).toEqual(true);
  expect(lifxProfile.metadata.requirements).toEqual([
    "aiolifx==1.2.1",
    "aiolifx-effects==0.3.2",
    "aiolifx-themes==1.0.2",
  ]);
  const localApi = lifxProfile.metadata.localApi as { status?: string; explicitUnsupported?: string[] };
  expect(localApi.status || '').toContain('UDP binary protocol');
  expect(localApi.explicitUnsupported?.some((entryArg) => entryArg.includes('aiolifx UDP binary protocol'))).toBeTrue();

  const runtime = await integration.setup({ name: "LIFX Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "lifx", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "lifx", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILifxSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("LIFX Device");

  const command = await runtime.callService!({ domain: "lifx", service: lifxProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
