import { expect, tap } from '@git.zone/tstest/tapbundle';
import { GraphiteClient, GraphiteConfigFlow, GraphiteIntegration, GraphiteMapper, HomeAssistantGraphiteIntegration, createGraphiteDiscoveryDescriptor, graphiteProfile, type IGraphiteSnapshot, type TGraphiteRawData } from '../../ts/integrations/graphite/index.js';

const rawData: TGraphiteRawData = {
  host: '127.0.0.1',
  port: 2003,
  protocol: 'tcp',
  prefix: 'ha',
  metrics: [
    'ha.sensor.temperature.state 21.5 1710000000',
  ],
};

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

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

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

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

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

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.device.port).toEqual(2003);
  expect(devices[0].integrationDomain).toEqual('graphite');
  expect(devices[0].manufacturer).toEqual('Graphite');
  expect(entities.some((entityArg) => entityArg.uniqueId.endsWith('_metric_lines') && entityArg.state === 1)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'binary_sensor' && entityArg.name === 'Configured')).toBeTrue();
});

tap.test('exposes Graphite runtime, HA alias, and unsupported metric send without executor', async () => {
  const integration = new GraphiteIntegration();
  const alias = new HomeAssistantGraphiteIntegration();
  expect(alias instanceof GraphiteIntegration).toBeTrue();
  expect(alias.domain).toEqual('graphite');
  expect(integration.status).toEqual('control-runtime');
  expect(graphiteProfile.metadata.configFlow).toEqual(false);
  expect(graphiteProfile.metadata.qualityScale).toEqual('legacy');

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

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

  const command = await runtime.callService!({ domain: 'graphite', service: 'send_metric', target: {}, data: { metric: 'ha.test 1 1710000000' } });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();
