import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantInsteonIntegration, InsteonClient, InsteonConfigFlow, InsteonIntegration, InsteonMapper, createInsteonDiscoveryDescriptor, insteonProfile, type IInsteonSnapshot, type TInsteonRawData } from '../../ts/integrations/insteon/index.js';

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

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

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

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

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

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

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

tap.test('exposes Insteon runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new InsteonIntegration();
  const alias = new HomeAssistantInsteonIntegration();
  expect(alias instanceof InsteonIntegration).toBeTrue();
  expect(alias.domain).toEqual("insteon");
  expect(integration.status).toEqual("control-runtime");
  expect(insteonProfile.metadata.configFlow).toEqual(true);
  expect(insteonProfile.metadata.requirements).toEqual([
    "pyinsteon==1.6.4",
    "insteon-frontend-home-assistant==0.6.2",
  ]);
  expect(((insteonProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported).join(' ')).toContain('pyinsteon');
  expect(((insteonProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported).join(' ')).toContain('binary framing');

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

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

  const command = await runtime.callService!({ domain: "insteon", service: insteonProfile.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();
