import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GpsdClient, GpsdConfigFlow, GpsdIntegration, GpsdMapper, HomeAssistantGpsdIntegration, createGpsdDiscoveryDescriptor, gpsdProfile, type IGpsdSnapshot, type TGpsdRawData } from '../../ts/integrations/gpsd/index.js';

const rawData: TGpsdRawData = {
  mode: 3,
  lat: 52.52,
  lon: 13.405,
  alt: 35.4,
  time: '2026-05-11T10:00:00Z',
  speed: 1.4,
  climb: 0.1,
  satellites: [
    { used: true },
    { used: false },
    { used: true },
  ],
};

tap.test('matches manual GPSD candidates and creates config flow output', async () => {
  const descriptor = createGpsdDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'gpsd-manual-match');
  const result = await matcher!.matches({ source: 'manual', host: '127.0.0.1', port: 2947, name: 'GPS 127.0.0.1', metadata: { rawData } }, {});

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

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

  const done = await (await new GpsdConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('127.0.0.1');
  expect(done.config?.port).toEqual(2947);
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps GPSD raw snapshots to runtime devices and entities', async () => {
  const client = new GpsdClient({ host: '127.0.0.1', port: 2947, rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = GpsdMapper.toSnapshotFromRaw({ host: '127.0.0.1', port: 2947 }, rawData);
  const devices = GpsdMapper.toDevices(mappedSnapshot);
  const entities = GpsdMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.device.port).toEqual(2947);
  expect(devices[0].integrationDomain).toEqual('gpsd');
  expect(devices[0].manufacturer).toEqual('GPSD');
  expect(entities.some((entityArg) => entityArg.uniqueId.endsWith('_mode') && entityArg.state === '3d_fix')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.uniqueId.endsWith('_used_satellites') && entityArg.state === 2)).toBeTrue();
});

tap.test('exposes GPSD read-only runtime, HA alias, and unsupported control', async () => {
  const integration = new GpsdIntegration();
  const alias = new HomeAssistantGpsdIntegration();
  expect(alias instanceof GpsdIntegration).toBeTrue();
  expect(alias.domain).toEqual('gpsd');
  expect(integration.status).toEqual('read-only-runtime');
  expect(gpsdProfile.metadata.configFlow).toEqual(true);
  expect(gpsdProfile.metadata.requirements).toEqual(['gps3==0.33.3']);

  const runtime = await integration.setup({ host: '127.0.0.1', port: 2947, rawData }, {});
  const status = await runtime.callService!({ domain: 'gpsd', service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: 'gpsd', service: 'refresh', target: {} });
  const snapshot = status.data as IGpsdSnapshot;

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

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