import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KwbClient, KwbConfigFlow, KwbIntegration, KwbMapper, createKwbDiscoveryDescriptor, kwbProfile, type IKwbSnapshot, type TKwbRawData } from '../../ts/integrations/kwb/index.js';

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

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

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

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

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

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

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

tap.test('exposes KWB Easyfire runtime and unsupported control without executor', async () => {
  const integration = new KwbIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(kwbProfile.metadata.configFlow).toEqual(false);
  expect(kwbProfile.metadata.requirements).toEqual([
    "pykwb==0.0.8",
  ]);

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

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

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