import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FirmataClient, FirmataConfigFlow, FirmataIntegration, FirmataMapper, HomeAssistantFirmataIntegration, createFirmataDiscoveryDescriptor, firmataProfile, type IFirmataSnapshot } from '../../ts/integrations/firmata/index.js';

const rawData = {
  device: {
    id: 'firmata-usb0',
    name: 'Firmata USB0',
    manufacturer: 'Firmata',
    model: 'Arduino Firmata',
    serialNumber: '/dev/ttyUSB0',
  },
  entities: [
    { id: 'analog_a0', name: 'Analog A0', platform: 'sensor', state: 512, unit: 'raw' },
    { id: 'door_input', name: 'Door Input', platform: 'binary_sensor', state: true },
    { id: 'relay_8', name: 'Relay 8', platform: 'switch', state: false, writable: true },
    { id: 'status_led', name: 'Status LED', platform: 'light', state: 128, writable: true },
  ],
};

tap.test('matches manual Firmata candidates and creates config flow output', async () => {
  const descriptor = createFirmataDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'firmata-manual-match');
  const result = await matcher!.matches({ name: 'Firmata USB0', metadata: { rawData, serialPort: '/dev/ttyUSB0' } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('firmata');

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

  const done = await (await new FirmataConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.name).toEqual('Firmata USB0');
  expect(done.config?.transport).toEqual('snapshot');
});

tap.test('maps Firmata raw snapshots to runtime devices and entities', async () => {
  const client = new FirmataClient({ rawData });
  const snapshot = await client.getSnapshot();
  const devices = FirmataMapper.toDevices(snapshot);
  const entities = FirmataMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('firmata');
  expect(devices[0].manufacturer).toEqual('Firmata');
  expect(entities.length).toEqual(4);
  expect(entities.some((entityArg) => entityArg.platform === 'switch')).toBeTrue();
});

tap.test('exposes Firmata executor-gated runtime, HA alias, and unsupported control', async () => {
  const integration = new FirmataIntegration();
  const alias = new HomeAssistantFirmataIntegration();
  expect(alias.domain).toEqual('firmata');
  expect(integration.status).toEqual('control-runtime');
  expect(firmataProfile.metadata.configFlow).toEqual(false);
  expect(firmataProfile.metadata.requirements).toEqual(['pymata-express==1.19']);

  const runtime = await integration.setup({ name: 'Firmata Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'firmata', service: 'status', target: {} });
  const snapshot = status.data as IFirmataSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Firmata USB0');

  const command = await runtime.callService!({ domain: 'switch', service: 'turn_on', target: { entityId: 'switch.firmata_runtime_relay_8' } });
  expect(command.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await integration.setup({
    name: 'Firmata Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service, target: requestArg.target } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'switch', service: 'turn_on', target: { entityId: 'switch.firmata_executor_relay_8' } });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
