import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantNetdataIntegration, NetdataClient, NetdataConfigFlow, NetdataIntegration, NetdataMapper, createNetdataDiscoveryDescriptor, netdataProfile, type INetdataSnapshot, type TNetdataRawData } from '../../ts/integrations/netdata/index.js';

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

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

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

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

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

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

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

tap.test('polls Netdata allmetrics and alarms over local HTTP', async () => {
  const requestedUrls: string[] = [];
  const server = createServer((requestArg, responseArg) => {
    requestedUrls.push(requestArg.url || '');
    responseArg.setHeader('content-type', 'application/json');
    if (requestArg.url?.startsWith('/api/v1/allmetrics?')) {
      responseArg.end(JSON.stringify({
        'system.load': {
          units: 'load',
          dimensions: { load15: { name: 'load15', value: 0.424 } },
        },
        'system.cpu': {
          units: 'percentage',
          dimensions: { user: { name: 'user', value: 12.345 } },
        },
      }));
      return;
    }
    if (requestArg.url?.startsWith('/api/v1/alarms?')) {
      responseArg.end(JSON.stringify({
        alarms: {
          cpu_hot: { recipient: 'sysadmin', status: 'CRITICAL' },
          muted: { recipient: 'silent', status: 'WARNING' },
        },
      }));
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end(JSON.stringify({ error: 'not found' }));
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const client = new NetdataClient({
      host: '127.0.0.1',
      port,
      timeoutMs: 1000,
      resources: {
        load: { data_group: 'system.load', element: 'load15' },
        cpu_user: { dataGroup: 'system.cpu', element: 'user', invert: true },
      },
    });
    const snapshot = await client.getSnapshot(true);

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.port).toEqual(port);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'load')?.state).toEqual(0.42);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'cpu_user')?.state).toEqual(-12.35);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'cpu_user')?.unit).toEqual('%');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'alarms')?.state).toEqual('critical');
    expect(requestedUrls.some((urlArg) => urlArg.startsWith('/api/v1/allmetrics?format=json'))).toBeTrue();
    expect(requestedUrls.some((urlArg) => urlArg.startsWith('/api/v1/alarms?all'))).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

tap.test('exposes Netdata runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new NetdataIntegration();
  const alias = new HomeAssistantNetdataIntegration();
  expect(alias instanceof NetdataIntegration).toBeTrue();
  expect(alias.domain).toEqual("netdata");
  expect(integration.status).toEqual("read-only-runtime");
  expect(netdataProfile.metadata.configFlow).toEqual(false);
  expect(netdataProfile.metadata.requirements).toEqual([
    "netdata==1.3.0",
  ]);
  expect((netdataProfile.metadata.localApi as { implemented: string[] }).implemented.some((itemArg) => itemArg.includes('/api/v1/allmetrics') && itemArg.includes('/api/v1/alarms'))).toBeTrue();

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

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

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