import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KeyboardRemoteClient, KeyboardRemoteConfigFlow, KeyboardRemoteIntegration, KeyboardRemoteMapper, createKeyboardRemoteDiscoveryDescriptor, keyboardRemoteProfile, type IKeyboardRemoteSnapshot, type TKeyboardRemoteRawData } from '../../ts/integrations/keyboard_remote/index.js';

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

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

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

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

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

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

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

tap.test('exposes Keyboard Remote runtime and unsupported control without executor', async () => {
  const integration = new KeyboardRemoteIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(keyboardRemoteProfile.metadata.configFlow).toEqual(false);
  expect(keyboardRemoteProfile.metadata.requirements).toEqual([
    "evdev==1.9.3",
    "asyncinotify==4.4.4",
  ]);
  expect((keyboardRemoteProfile.metadata.localApi as { explicitUnsupported: string[] }).explicitUnsupported.some((itemArg) => itemArg.includes('no evdev/inotify/ioctl stack'))).toBeTrue();

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

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

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