import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNumatoIntegration, NumatoClient, NumatoConfigFlow, NumatoIntegration, NumatoMapper, createNumatoDiscoveryDescriptor, numatoProfile, type INumatoSnapshot, type TNumatoRawData } from '../../ts/integrations/numato/index.js';

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

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

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

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

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

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

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

tap.test('exposes Numato USB GPIO Expander runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NumatoIntegration();
  const alias = new HomeAssistantNumatoIntegration();
  expect(alias instanceof NumatoIntegration).toBeTrue();
  expect(alias.domain).toEqual("numato");
  expect(integration.status).toEqual("control-runtime");
  expect(numatoProfile.metadata.configFlow).toEqual(false);
  expect(numatoProfile.metadata.requirements).toEqual([
    "numato-gpio==0.13.0",
  ]);
  expect(JSON.stringify(numatoProfile.metadata.localApi)).toContain('numato-gpio/pyserial serial stack');

  const runtime = await integration.setup({ name: "Numato USB GPIO Expander Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "numato", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "numato", service: 'refresh', target: {} });
  const snapshot = statusResult.data as INumatoSnapshot;

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

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